This is cgi1.py"
diff --git a/Demo/cgi/cgi2.py b/Demo/cgi/cgi2.py
deleted file mode 100755
index d956f6538c..0000000000
--- a/Demo/cgi/cgi2.py
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/usr/local/bin/python
-
-"""CGI test 2 - basic use of cgi module."""
-
-import cgitb; cgitb.enable()
-
-import cgi
-
-def main():
- form = cgi.FieldStorage()
- print "Content-type: text/html"
- print
- if not form:
- print "
No Form Keys
"
- else:
- print "
Form Keys
"
- for key in form.keys():
- value = form[key].value
- print "
", cgi.escape(key), ":", cgi.escape(value)
-
-if __name__ == "__main__":
- main()
diff --git a/Demo/cgi/cgi3.py b/Demo/cgi/cgi3.py
deleted file mode 100755
index a3421b5b2d..0000000000
--- a/Demo/cgi/cgi3.py
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/usr/local/bin/python
-
-"""CGI test 3 (persistent data)."""
-
-import cgitb; cgitb.enable()
-
-from wiki import main
-
-if __name__ == "__main__":
- main()
diff --git a/Demo/cgi/wiki.py b/Demo/cgi/wiki.py
deleted file mode 100644
index ee094a8ef8..0000000000
--- a/Demo/cgi/wiki.py
+++ /dev/null
@@ -1,123 +0,0 @@
-"""Wiki main program. Imported and run by cgi3.py."""
-
-import os, re, cgi, sys, tempfile
-escape = cgi.escape
-
-def main():
- form = cgi.FieldStorage()
- print "Content-type: text/html"
- print
- cmd = form.getvalue("cmd", "view")
- page = form.getvalue("page", "FrontPage")
- wiki = WikiPage(page)
- method = getattr(wiki, 'cmd_' + cmd, None) or wiki.cmd_view
- method(form)
-
-class WikiPage:
-
- homedir = tempfile.gettempdir()
- scripturl = os.path.basename(sys.argv[0])
-
- def __init__(self, name):
- if not self.iswikiword(name):
- raise ValueError, "page name is not a wiki word"
- self.name = name
- self.load()
-
- def cmd_view(self, form):
- print "
", escape(self.splitwikiword(self.name)), "
"
- print "
"
- for line in self.data.splitlines():
- line = line.rstrip()
- if not line:
- print "
"
- else:
- print self.formatline(line)
- print "
"
- print "
", self.mklink("edit", self.name, "Edit this page") + ";"
- print self.mklink("view", "FrontPage", "go to front page") + "."
-
- def formatline(self, line):
- words = []
- for word in re.split('(\W+)', line):
- if self.iswikiword(word):
- if os.path.isfile(self.mkfile(word)):
- word = self.mklink("view", word, word)
- else:
- word = self.mklink("new", word, word + "*")
- else:
- word = escape(word)
- words.append(word)
- return "".join(words)
-
- def cmd_edit(self, form, label="Change"):
- print "
An error occurred while attempting to write the file:"
- print "
", escape(error)
- else:
- # Use a redirect directive, to avoid "reload page" problems
- print "
"
- s = ''
- print s % (self.scripturl + "?cmd=view&page=" + self.name)
- print ""
- print "
OK
"
- print "
If nothing happens, please click here:",
- print self.mklink("view", self.name, self.name)
-
- def cmd_new(self, form):
- self.cmd_edit(form, label="Create")
-
- def iswikiword(self, word):
- return re.match("[A-Z][a-z]+([A-Z][a-z]*)+", word)
-
- def splitwikiword(self, word):
- chars = []
- for c in word:
- if chars and c.isupper():
- chars.append(' ')
- chars.append(c)
- return "".join(chars)
-
- def mkfile(self, name=None):
- if name is None:
- name = self.name
- return os.path.join(self.homedir, name + ".txt")
-
- def mklink(self, cmd, page, text):
- link = self.scripturl + "?cmd=" + cmd + "&page=" + page
- return '%s' % (link, text)
-
- def load(self):
- try:
- f = open(self.mkfile())
- data = f.read().strip()
- f.close()
- except IOError:
- data = ""
- self.data = data
-
- def store(self):
- data = self.data
- try:
- f = open(self.mkfile(), "w")
- f.write(data)
- if data and not data.endswith('\n'):
- f.write('\n')
- f.close()
- return ""
- except IOError, err:
- return "IOError: %s" % str(err)
diff --git a/Demo/classes/Complex.py b/Demo/classes/Complex.py
deleted file mode 100755
index 4585f62f44..0000000000
--- a/Demo/classes/Complex.py
+++ /dev/null
@@ -1,298 +0,0 @@
-# Complex numbers
-# ---------------
-
-# [Now that Python has a complex data type built-in, this is not very
-# useful, but it's still a nice example class]
-
-# This module represents complex numbers as instances of the class Complex.
-# A Complex instance z has two data attribues, z.re (the real part) and z.im
-# (the imaginary part). In fact, z.re and z.im can have any value -- all
-# arithmetic operators work regardless of the type of z.re and z.im (as long
-# as they support numerical operations).
-#
-# The following functions exist (Complex is actually a class):
-# Complex([re [,im]) -> creates a complex number from a real and an imaginary part
-# IsComplex(z) -> true iff z is a complex number (== has .re and .im attributes)
-# ToComplex(z) -> a complex number equal to z; z itself if IsComplex(z) is true
-# if z is a tuple(re, im) it will also be converted
-# PolarToComplex([r [,phi [,fullcircle]]]) ->
-# the complex number z for which r == z.radius() and phi == z.angle(fullcircle)
-# (r and phi default to 0)
-# exp(z) -> returns the complex exponential of z. Equivalent to pow(math.e,z).
-#
-# Complex numbers have the following methods:
-# z.abs() -> absolute value of z
-# z.radius() == z.abs()
-# z.angle([fullcircle]) -> angle from positive X axis; fullcircle gives units
-# z.phi([fullcircle]) == z.angle(fullcircle)
-#
-# These standard functions and unary operators accept complex arguments:
-# abs(z)
-# -z
-# +z
-# not z
-# repr(z) == `z`
-# str(z)
-# hash(z) -> a combination of hash(z.re) and hash(z.im) such that if z.im is zero
-# the result equals hash(z.re)
-# Note that hex(z) and oct(z) are not defined.
-#
-# These conversions accept complex arguments only if their imaginary part is zero:
-# int(z)
-# long(z)
-# float(z)
-#
-# The following operators accept two complex numbers, or one complex number
-# and one real number (int, long or float):
-# z1 + z2
-# z1 - z2
-# z1 * z2
-# z1 / z2
-# pow(z1, z2)
-# cmp(z1, z2)
-# Note that z1 % z2 and divmod(z1, z2) are not defined,
-# nor are shift and mask operations.
-#
-# The standard module math does not support complex numbers.
-# (I suppose it would be easy to implement a cmath module.)
-#
-# Idea:
-# add a class Polar(r, phi) and mixed-mode arithmetic which
-# chooses the most appropriate type for the result:
-# Complex for +,-,cmp
-# Polar for *,/,pow
-
-
-import types, math
-
-twopi = math.pi*2.0
-halfpi = math.pi/2.0
-
-def IsComplex(obj):
- return hasattr(obj, 're') and hasattr(obj, 'im')
-
-def ToComplex(obj):
- if IsComplex(obj):
- return obj
- elif type(obj) == types.TupleType:
- return apply(Complex, obj)
- else:
- return Complex(obj)
-
-def PolarToComplex(r = 0, phi = 0, fullcircle = twopi):
- phi = phi * (twopi / fullcircle)
- return Complex(math.cos(phi)*r, math.sin(phi)*r)
-
-def Re(obj):
- if IsComplex(obj):
- return obj.re
- else:
- return obj
-
-def Im(obj):
- if IsComplex(obj):
- return obj.im
- else:
- return obj
-
-class Complex:
-
- def __init__(self, re=0, im=0):
- if IsComplex(re):
- im = i + Complex(0, re.im)
- re = re.re
- if IsComplex(im):
- re = re - im.im
- im = im.re
- self.__dict__['re'] = re
- self.__dict__['im'] = im
-
- def __setattr__(self, name, value):
- raise TypeError, 'Complex numbers are immutable'
-
- def __hash__(self):
- if not self.im: return hash(self.re)
- mod = sys.maxint + 1L
- return int((hash(self.re) + 2L*hash(self.im) + mod) % (2L*mod) - mod)
-
- def __repr__(self):
- if not self.im:
- return 'Complex(%s)' % `self.re`
- else:
- return 'Complex(%s, %s)' % (`self.re`, `self.im`)
-
- def __str__(self):
- if not self.im:
- return `self.re`
- else:
- return 'Complex(%s, %s)' % (`self.re`, `self.im`)
-
- def __neg__(self):
- return Complex(-self.re, -self.im)
-
- def __pos__(self):
- return self
-
- def __abs__(self):
- # XXX could be done differently to avoid overflow!
- return math.sqrt(self.re*self.re + self.im*self.im)
-
- def __int__(self):
- if self.im:
- raise ValueError, "can't convert Complex with nonzero im to int"
- return int(self.re)
-
- def __long__(self):
- if self.im:
- raise ValueError, "can't convert Complex with nonzero im to long"
- return long(self.re)
-
- def __float__(self):
- if self.im:
- raise ValueError, "can't convert Complex with nonzero im to float"
- return float(self.re)
-
- def __cmp__(self, other):
- other = ToComplex(other)
- return cmp((self.re, self.im), (other.re, other.im))
-
- def __rcmp__(self, other):
- other = ToComplex(other)
- return cmp(other, self)
-
- def __nonzero__(self):
- return not (self.re == self.im == 0)
-
- abs = radius = __abs__
-
- def angle(self, fullcircle = twopi):
- return (fullcircle/twopi) * ((halfpi - math.atan2(self.re, self.im)) % twopi)
-
- phi = angle
-
- def __add__(self, other):
- other = ToComplex(other)
- return Complex(self.re + other.re, self.im + other.im)
-
- __radd__ = __add__
-
- def __sub__(self, other):
- other = ToComplex(other)
- return Complex(self.re - other.re, self.im - other.im)
-
- def __rsub__(self, other):
- other = ToComplex(other)
- return other - self
-
- def __mul__(self, other):
- other = ToComplex(other)
- return Complex(self.re*other.re - self.im*other.im,
- self.re*other.im + self.im*other.re)
-
- __rmul__ = __mul__
-
- def __div__(self, other):
- other = ToComplex(other)
- d = float(other.re*other.re + other.im*other.im)
- if not d: raise ZeroDivisionError, 'Complex division'
- return Complex((self.re*other.re + self.im*other.im) / d,
- (self.im*other.re - self.re*other.im) / d)
-
- def __rdiv__(self, other):
- other = ToComplex(other)
- return other / self
-
- def __pow__(self, n, z=None):
- if z is not None:
- raise TypeError, 'Complex does not support ternary pow()'
- if IsComplex(n):
- if n.im:
- if self.im: raise TypeError, 'Complex to the Complex power'
- else: return exp(math.log(self.re)*n)
- n = n.re
- r = pow(self.abs(), n)
- phi = n*self.angle()
- return Complex(math.cos(phi)*r, math.sin(phi)*r)
-
- def __rpow__(self, base):
- base = ToComplex(base)
- return pow(base, self)
-
-def exp(z):
- r = math.exp(z.re)
- return Complex(math.cos(z.im)*r,math.sin(z.im)*r)
-
-
-def checkop(expr, a, b, value, fuzz = 1e-6):
- import sys
- print ' ', a, 'and', b,
- try:
- result = eval(expr)
- except:
- result = sys.exc_type
- print '->', result
- if (type(result) == type('') or type(value) == type('')):
- ok = result == value
- else:
- ok = abs(result - value) <= fuzz
- if not ok:
- print '!!\t!!\t!! should be', value, 'diff', abs(result - value)
-
-
-def test():
- testsuite = {
- 'a+b': [
- (1, 10, 11),
- (1, Complex(0,10), Complex(1,10)),
- (Complex(0,10), 1, Complex(1,10)),
- (Complex(0,10), Complex(1), Complex(1,10)),
- (Complex(1), Complex(0,10), Complex(1,10)),
- ],
- 'a-b': [
- (1, 10, -9),
- (1, Complex(0,10), Complex(1,-10)),
- (Complex(0,10), 1, Complex(-1,10)),
- (Complex(0,10), Complex(1), Complex(-1,10)),
- (Complex(1), Complex(0,10), Complex(1,-10)),
- ],
- 'a*b': [
- (1, 10, 10),
- (1, Complex(0,10), Complex(0, 10)),
- (Complex(0,10), 1, Complex(0,10)),
- (Complex(0,10), Complex(1), Complex(0,10)),
- (Complex(1), Complex(0,10), Complex(0,10)),
- ],
- 'a/b': [
- (1., 10, 0.1),
- (1, Complex(0,10), Complex(0, -0.1)),
- (Complex(0, 10), 1, Complex(0, 10)),
- (Complex(0, 10), Complex(1), Complex(0, 10)),
- (Complex(1), Complex(0,10), Complex(0, -0.1)),
- ],
- 'pow(a,b)': [
- (1, 10, 1),
- (1, Complex(0,10), 1),
- (Complex(0,10), 1, Complex(0,10)),
- (Complex(0,10), Complex(1), Complex(0,10)),
- (Complex(1), Complex(0,10), 1),
- (2, Complex(4,0), 16),
- ],
- 'cmp(a,b)': [
- (1, 10, -1),
- (1, Complex(0,10), 1),
- (Complex(0,10), 1, -1),
- (Complex(0,10), Complex(1), -1),
- (Complex(1), Complex(0,10), 1),
- ],
- }
- exprs = testsuite.keys()
- exprs.sort()
- for expr in exprs:
- print expr + ':'
- t = (expr,)
- for item in testsuite[expr]:
- apply(checkop, t+item)
-
-
-if __name__ == '__main__':
- test()
diff --git a/Demo/classes/Dates.py b/Demo/classes/Dates.py
deleted file mode 100755
index 2c37a4e3bf..0000000000
--- a/Demo/classes/Dates.py
+++ /dev/null
@@ -1,218 +0,0 @@
-# Class Date supplies date objects that support date arithmetic.
-#
-# Date(month,day,year) returns a Date object. An instance prints as,
-# e.g., 'Mon 16 Aug 1993'.
-#
-# Addition, subtraction, comparison operators, min, max, and sorting
-# all work as expected for date objects: int+date or date+int returns
-# the date `int' days from `date'; date+date raises an exception;
-# date-int returns the date `int' days before `date'; date2-date1 returns
-# an integer, the number of days from date1 to date2; int-date raises an
-# exception; date1 < date2 is true iff date1 occurs before date2 (&
-# similarly for other comparisons); min(date1,date2) is the earlier of
-# the two dates and max(date1,date2) the later; and date objects can be
-# used as dictionary keys.
-#
-# Date objects support one visible method, date.weekday(). This returns
-# the day of the week the date falls on, as a string.
-#
-# Date objects also have 4 read-only data attributes:
-# .month in 1..12
-# .day in 1..31
-# .year int or long int
-# .ord the ordinal of the date relative to an arbitrary staring point
-#
-# The Dates module also supplies function today(), which returns the
-# current date as a date object.
-#
-# Those entranced by calendar trivia will be disappointed, as no attempt
-# has been made to accommodate the Julian (etc) system. On the other
-# hand, at least this package knows that 2000 is a leap year but 2100
-# isn't, and works fine for years with a hundred decimal digits .
-
-# Tim Peters tim@ksr.com
-# not speaking for Kendall Square Research Corp
-
-# Adapted to Python 1.1 (where some hacks to overcome coercion are unnecessary)
-# by Guido van Rossum
-
-# vi:set tabsize=8:
-
-_MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May',
- 'June', 'July', 'August', 'September', 'October',
- 'November', 'December' ]
-
-_DAY_NAMES = [ 'Friday', 'Saturday', 'Sunday', 'Monday',
- 'Tuesday', 'Wednesday', 'Thursday' ]
-
-_DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]
-
-_DAYS_BEFORE_MONTH = []
-dbm = 0
-for dim in _DAYS_IN_MONTH:
- _DAYS_BEFORE_MONTH.append(dbm)
- dbm = dbm + dim
-del dbm, dim
-
-_INT_TYPES = type(1), type(1L)
-
-def _is_leap( year ): # 1 if leap year, else 0
- if year % 4 != 0: return 0
- if year % 400 == 0: return 1
- return year % 100 != 0
-
-def _days_in_year( year ): # number of days in year
- return 365 + _is_leap(year)
-
-def _days_before_year( year ): # number of days before year
- return year*365L + (year+3)/4 - (year+99)/100 + (year+399)/400
-
-def _days_in_month( month, year ): # number of days in month of year
- if month == 2 and _is_leap(year): return 29
- return _DAYS_IN_MONTH[month-1]
-
-def _days_before_month( month, year ): # number of days in year before month
- return _DAYS_BEFORE_MONTH[month-1] + (month > 2 and _is_leap(year))
-
-def _date2num( date ): # compute ordinal of date.month,day,year
- return _days_before_year( date.year ) + \
- _days_before_month( date.month, date.year ) + \
- date.day
-
-_DI400Y = _days_before_year( 400 ) # number of days in 400 years
-
-def _num2date( n ): # return date with ordinal n
- if type(n) not in _INT_TYPES:
- raise TypeError, 'argument must be integer: ' + `type(n)`
-
- ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj
- del ans.ord, ans.month, ans.day, ans.year # un-initialize it
- ans.ord = n
-
- n400 = (n-1)/_DI400Y # # of 400-year blocks preceding
- year, n = 400 * n400, n - _DI400Y * n400
- more = n / 365
- dby = _days_before_year( more )
- if dby >= n:
- more = more - 1
- dby = dby - _days_in_year( more )
- year, n = year + more, int(n - dby)
-
- try: year = int(year) # chop to int, if it fits
- except (ValueError, OverflowError): pass
-
- month = min( n/29 + 1, 12 )
- dbm = _days_before_month( month, year )
- if dbm >= n:
- month = month - 1
- dbm = dbm - _days_in_month( month, year )
-
- ans.month, ans.day, ans.year = month, n-dbm, year
- return ans
-
-def _num2day( n ): # return weekday name of day with ordinal n
- return _DAY_NAMES[ int(n % 7) ]
-
-
-class Date:
- def __init__( self, month, day, year ):
- if not 1 <= month <= 12:
- raise ValueError, 'month must be in 1..12: ' + `month`
- dim = _days_in_month( month, year )
- if not 1 <= day <= dim:
- raise ValueError, 'day must be in 1..' + `dim` + ': ' + `day`
- self.month, self.day, self.year = month, day, year
- self.ord = _date2num( self )
-
- # don't allow setting existing attributes
- def __setattr__( self, name, value ):
- if self.__dict__.has_key(name):
- raise AttributeError, 'read-only attribute ' + name
- self.__dict__[name] = value
-
- def __cmp__( self, other ):
- return cmp( self.ord, other.ord )
-
- # define a hash function so dates can be used as dictionary keys
- def __hash__( self ):
- return hash( self.ord )
-
- # print as, e.g., Mon 16 Aug 1993
- def __repr__( self ):
- return '%.3s %2d %.3s ' % (
- self.weekday(),
- self.day,
- _MONTH_NAMES[self.month-1] ) + `self.year`
-
- # Python 1.1 coerces neither int+date nor date+int
- def __add__( self, n ):
- if type(n) not in _INT_TYPES:
- raise TypeError, 'can\'t add ' + `type(n)` + ' to date'
- return _num2date( self.ord + n )
- __radd__ = __add__ # handle int+date
-
- # Python 1.1 coerces neither date-int nor date-date
- def __sub__( self, other ):
- if type(other) in _INT_TYPES: # date-int
- return _num2date( self.ord - other )
- else:
- return self.ord - other.ord # date-date
-
- # complain about int-date
- def __rsub__( self, other ):
- raise TypeError, 'Can\'t subtract date from integer'
-
- def weekday( self ):
- return _num2day( self.ord )
-
-def today():
- import time
- local = time.localtime(time.time())
- return Date( local[1], local[2], local[0] )
-
-DateTestError = 'DateTestError'
-def test( firstyear, lastyear ):
- a = Date(9,30,1913)
- b = Date(9,30,1914)
- if `a` != 'Tue 30 Sep 1913':
- raise DateTestError, '__repr__ failure'
- if (not a < b) or a == b or a > b or b != b:
- raise DateTestError, '__cmp__ failure'
- if a+365 != b or 365+a != b:
- raise DateTestError, '__add__ failure'
- if b-a != 365 or b-365 != a:
- raise DateTestError, '__sub__ failure'
- try:
- x = 1 - a
- raise DateTestError, 'int-date should have failed'
- except TypeError:
- pass
- try:
- x = a + b
- raise DateTestError, 'date+date should have failed'
- except TypeError:
- pass
- if a.weekday() != 'Tuesday':
- raise DateTestError, 'weekday() failure'
- if max(a,b) is not b or min(a,b) is not a:
- raise DateTestError, 'min/max failure'
- d = {a-1:b, b:a+1}
- if d[b-366] != b or d[a+(b-a)] != Date(10,1,1913):
- raise DateTestError, 'dictionary failure'
-
- # verify date<->number conversions for first and last days for
- # all years in firstyear .. lastyear
-
- lord = _days_before_year( firstyear )
- y = firstyear
- while y <= lastyear:
- ford = lord + 1
- lord = ford + _days_in_year(y) - 1
- fd, ld = Date(1,1,y), Date(12,31,y)
- if (fd.ord,ld.ord) != (ford,lord):
- raise DateTestError, ('date->num failed', y)
- fd, ld = _num2date(ford), _num2date(lord)
- if (1,1,y,12,31,y) != \
- (fd.month,fd.day,fd.year,ld.month,ld.day,ld.year):
- raise DateTestError, ('num->date failed', y)
- y = y + 1
diff --git a/Demo/classes/Dbm.py b/Demo/classes/Dbm.py
deleted file mode 100755
index 5566f999ad..0000000000
--- a/Demo/classes/Dbm.py
+++ /dev/null
@@ -1,66 +0,0 @@
-# A wrapper around the (optional) built-in class dbm, supporting keys
-# and values of almost any type instead of just string.
-# (Actually, this works only for keys and values that can be read back
-# correctly after being converted to a string.)
-
-
-class Dbm:
-
- def __init__(self, filename, mode, perm):
- import dbm
- self.db = dbm.open(filename, mode, perm)
-
- def __repr__(self):
- s = ''
- for key in self.keys():
- t = `key` + ': ' + `self[key]`
- if s: t = ', ' + t
- s = s + t
- return '{' + s + '}'
-
- def __len__(self):
- return len(self.db)
-
- def __getitem__(self, key):
- return eval(self.db[`key`])
-
- def __setitem__(self, key, value):
- self.db[`key`] = `value`
-
- def __delitem__(self, key):
- del self.db[`key`]
-
- def keys(self):
- res = []
- for key in self.db.keys():
- res.append(eval(key))
- return res
-
- def has_key(self, key):
- return self.db.has_key(`key`)
-
-
-def test():
- d = Dbm('@dbm', 'rw', 0600)
- print d
- while 1:
- try:
- key = input('key: ')
- if d.has_key(key):
- value = d[key]
- print 'currently:', value
- value = input('value: ')
- if value == None:
- del d[key]
- else:
- d[key] = value
- except KeyboardInterrupt:
- print ''
- print d
- except EOFError:
- print '[eof]'
- break
- print d
-
-
-test()
diff --git a/Demo/classes/README b/Demo/classes/README
deleted file mode 100644
index 1d41f6af33..0000000000
--- a/Demo/classes/README
+++ /dev/null
@@ -1,13 +0,0 @@
-Examples of classes that implement special operators (see reference manual):
-
-Complex.py Complex numbers
-Dates.py Date manipulation package by Tim Peters
-Dbm.py Wrapper around built-in dbm, supporting arbitrary values
-Range.py Example of a generator: re-implement built-in range()
-Rat.py Rational numbers
-Rev.py Yield the reverse of a sequence
-Vec.py A simple vector class
-bitvec.py A bit-vector class by Jan-Hein B\"uhrman
-
-(For straightforward examples of basic class features, such as use of
-methods and inheritance, see the library code.)
diff --git a/Demo/classes/Range.py b/Demo/classes/Range.py
deleted file mode 100755
index ebd18177b2..0000000000
--- a/Demo/classes/Range.py
+++ /dev/null
@@ -1,71 +0,0 @@
-# Example of a generator: re-implement the built-in range function
-# without actually constructing the list of values. (It turns out
-# that the built-in function is about 20 times faster -- that's why
-# it's built-in. :-)
-
-
-# Wrapper function to emulate the complicated range() arguments
-
-def range(*a):
- if len(a) == 1:
- start, stop, step = 0, a[0], 1
- elif len(a) == 2:
- start, stop = a
- step = 1
- elif len(a) == 3:
- start, stop, step = a
- else:
- raise TypeError, 'range() needs 1-3 arguments'
- return Range(start, stop, step)
-
-
-# Class implementing a range object.
-# To the user the instances feel like immutable sequences
-# (and you can't concatenate or slice them)
-
-class Range:
-
- # initialization -- should be called only by range() above
- def __init__(self, start, stop, step):
- if step == 0:
- raise ValueError, 'range() called with zero step'
- self.start = start
- self.stop = stop
- self.step = step
- self.len = max(0, int((self.stop - self.start) / self.step))
-
- # implement `x` and is also used by print x
- def __repr__(self):
- return 'range' + `self.start, self.stop, self.step`
-
- # implement len(x)
- def __len__(self):
- return self.len
-
- # implement x[i]
- def __getitem__(self, i):
- if 0 <= i < self.len:
- return self.start + self.step * i
- else:
- raise IndexError, 'range[i] index out of range'
-
-
-# Small test program
-
-def test():
- import time, __builtin__
- print range(10), range(-10, 10), range(0, 10, 2)
- for i in range(100, -100, -10): print i,
- print
- t1 = time.time()
- for i in range(1000):
- pass
- t2 = time.time()
- for i in __builtin__.range(1000):
- pass
- t3 = time.time()
- print t2-t1, 'sec (class)'
- print t3-t2, 'sec (built-in)'
-
-
-test()
diff --git a/Demo/classes/Rat.py b/Demo/classes/Rat.py
deleted file mode 100755
index 55543b6d2d..0000000000
--- a/Demo/classes/Rat.py
+++ /dev/null
@@ -1,310 +0,0 @@
-'''\
-This module implements rational numbers.
-
-The entry point of this module is the function
- rat(numerator, denominator)
-If either numerator or denominator is of an integral or rational type,
-the result is a rational number, else, the result is the simplest of
-the types float and complex which can hold numerator/denominator.
-If denominator is omitted, it defaults to 1.
-Rational numbers can be used in calculations with any other numeric
-type. The result of the calculation will be rational if possible.
-
-There is also a test function with calling sequence
- test()
-The documentation string of the test function contains the expected
-output.
-'''
-
-# Contributed by Sjoerd Mullender
-
-from types import *
-
-def gcd(a, b):
- '''Calculate the Greatest Common Divisor.'''
- while b:
- a, b = b, a%b
- return a
-
-def rat(num, den = 1):
- # must check complex before float
- if isinstance(num, complex) or isinstance(den, complex):
- # numerator or denominator is complex: return a complex
- return complex(num) / complex(den)
- if isinstance(num, float) or isinstance(den, float):
- # numerator or denominator is float: return a float
- return float(num) / float(den)
- # otherwise return a rational
- return Rat(num, den)
-
-class Rat:
- '''This class implements rational numbers.'''
-
- def __init__(self, num, den = 1):
- if den == 0:
- raise ZeroDivisionError, 'rat(x, 0)'
-
- # normalize
-
- # must check complex before float
- if (isinstance(num, complex) or
- isinstance(den, complex)):
- # numerator or denominator is complex:
- # normalized form has denominator == 1+0j
- self.__num = complex(num) / complex(den)
- self.__den = complex(1)
- return
- if isinstance(num, float) or isinstance(den, float):
- # numerator or denominator is float:
- # normalized form has denominator == 1.0
- self.__num = float(num) / float(den)
- self.__den = 1.0
- return
- if (isinstance(num, self.__class__) or
- isinstance(den, self.__class__)):
- # numerator or denominator is rational
- new = num / den
- if not isinstance(new, self.__class__):
- self.__num = new
- if isinstance(new, complex):
- self.__den = complex(1)
- else:
- self.__den = 1.0
- else:
- self.__num = new.__num
- self.__den = new.__den
- else:
- # make sure numerator and denominator don't
- # have common factors
- # this also makes sure that denominator > 0
- g = gcd(num, den)
- self.__num = num / g
- self.__den = den / g
- # try making numerator and denominator of IntType if they fit
- try:
- numi = int(self.__num)
- deni = int(self.__den)
- except (OverflowError, TypeError):
- pass
- else:
- if self.__num == numi and self.__den == deni:
- self.__num = numi
- self.__den = deni
-
- def __repr__(self):
- return 'Rat(%s,%s)' % (self.__num, self.__den)
-
- def __str__(self):
- if self.__den == 1:
- return str(self.__num)
- else:
- return '(%s/%s)' % (str(self.__num), str(self.__den))
-
- # a + b
- def __add__(a, b):
- try:
- return rat(a.__num * b.__den + b.__num * a.__den,
- a.__den * b.__den)
- except OverflowError:
- return rat(long(a.__num) * long(b.__den) +
- long(b.__num) * long(a.__den),
- long(a.__den) * long(b.__den))
-
- def __radd__(b, a):
- return Rat(a) + b
-
- # a - b
- def __sub__(a, b):
- try:
- return rat(a.__num * b.__den - b.__num * a.__den,
- a.__den * b.__den)
- except OverflowError:
- return rat(long(a.__num) * long(b.__den) -
- long(b.__num) * long(a.__den),
- long(a.__den) * long(b.__den))
-
- def __rsub__(b, a):
- return Rat(a) - b
-
- # a * b
- def __mul__(a, b):
- try:
- return rat(a.__num * b.__num, a.__den * b.__den)
- except OverflowError:
- return rat(long(a.__num) * long(b.__num),
- long(a.__den) * long(b.__den))
-
- def __rmul__(b, a):
- return Rat(a) * b
-
- # a / b
- def __div__(a, b):
- try:
- return rat(a.__num * b.__den, a.__den * b.__num)
- except OverflowError:
- return rat(long(a.__num) * long(b.__den),
- long(a.__den) * long(b.__num))
-
- def __rdiv__(b, a):
- return Rat(a) / b
-
- # a % b
- def __mod__(a, b):
- div = a / b
- try:
- div = int(div)
- except OverflowError:
- div = long(div)
- return a - b * div
-
- def __rmod__(b, a):
- return Rat(a) % b
-
- # a ** b
- def __pow__(a, b):
- if b.__den != 1:
- if isinstance(a.__num, complex):
- a = complex(a)
- else:
- a = float(a)
- if isinstance(b.__num, complex):
- b = complex(b)
- else:
- b = float(b)
- return a ** b
- try:
- return rat(a.__num ** b.__num, a.__den ** b.__num)
- except OverflowError:
- return rat(long(a.__num) ** b.__num,
- long(a.__den) ** b.__num)
-
- def __rpow__(b, a):
- return Rat(a) ** b
-
- # -a
- def __neg__(a):
- try:
- return rat(-a.__num, a.__den)
- except OverflowError:
- # a.__num == sys.maxint
- return rat(-long(a.__num), a.__den)
-
- # abs(a)
- def __abs__(a):
- return rat(abs(a.__num), a.__den)
-
- # int(a)
- def __int__(a):
- return int(a.__num / a.__den)
-
- # long(a)
- def __long__(a):
- return long(a.__num) / long(a.__den)
-
- # float(a)
- def __float__(a):
- return float(a.__num) / float(a.__den)
-
- # complex(a)
- def __complex__(a):
- return complex(a.__num) / complex(a.__den)
-
- # cmp(a,b)
- def __cmp__(a, b):
- diff = Rat(a - b)
- if diff.__num < 0:
- return -1
- elif diff.__num > 0:
- return 1
- else:
- return 0
-
- def __rcmp__(b, a):
- return cmp(Rat(a), b)
-
- # a != 0
- def __nonzero__(a):
- return a.__num != 0
-
- # coercion
- def __coerce__(a, b):
- return a, Rat(b)
-
-def test():
- '''\
- Test function for rat module.
-
- The expected output is (module some differences in floating
- precission):
- -1
- -1
- 0 0L 0.1 (0.1+0j)
- [Rat(1,2), Rat(-3,10), Rat(1,25), Rat(1,4)]
- [Rat(-3,10), Rat(1,25), Rat(1,4), Rat(1,2)]
- 0
- (11/10)
- (11/10)
- 1.1
- OK
- 2 1.5 (3/2) (1.5+1.5j) (15707963/5000000)
- 2 2 2.0 (2+0j)
-
- 4 0 4 1 4 0
- 3.5 0.5 3.0 1.33333333333 2.82842712475 1
- (7/2) (1/2) 3 (4/3) 2.82842712475 1
- (3.5+1.5j) (0.5-1.5j) (3+3j) (0.666666666667-0.666666666667j) (1.43248815986+2.43884761145j) 1
- 1.5 1 1.5 (1.5+0j)
-
- 3.5 -0.5 3.0 0.75 2.25 -1
- 3.0 0.0 2.25 1.0 1.83711730709 0
- 3.0 0.0 2.25 1.0 1.83711730709 1
- (3+1.5j) -1.5j (2.25+2.25j) (0.5-0.5j) (1.50768393746+1.04970907623j) -1
- (3/2) 1 1.5 (1.5+0j)
-
- (7/2) (-1/2) 3 (3/4) (9/4) -1
- 3.0 0.0 2.25 1.0 1.83711730709 -1
- 3 0 (9/4) 1 1.83711730709 0
- (3+1.5j) -1.5j (2.25+2.25j) (0.5-0.5j) (1.50768393746+1.04970907623j) -1
- (1.5+1.5j) (1.5+1.5j)
-
- (3.5+1.5j) (-0.5+1.5j) (3+3j) (0.75+0.75j) 4.5j -1
- (3+1.5j) 1.5j (2.25+2.25j) (1+1j) (1.18235814075+2.85446505899j) 1
- (3+1.5j) 1.5j (2.25+2.25j) (1+1j) (1.18235814075+2.85446505899j) 1
- (3+3j) 0j 4.5j (1+0j) (-0.638110484918+0.705394566962j) 0
- '''
- print rat(-1L, 1)
- print rat(1, -1)
- a = rat(1, 10)
- print int(a), long(a), float(a), complex(a)
- b = rat(2, 5)
- l = [a+b, a-b, a*b, a/b]
- print l
- l.sort()
- print l
- print rat(0, 1)
- print a+1
- print a+1L
- print a+1.0
- try:
- print rat(1, 0)
- raise SystemError, 'should have been ZeroDivisionError'
- except ZeroDivisionError:
- print 'OK'
- print rat(2), rat(1.5), rat(3, 2), rat(1.5+1.5j), rat(31415926,10000000)
- list = [2, 1.5, rat(3,2), 1.5+1.5j]
- for i in list:
- print i,
- if not isinstance(i, complex):
- print int(i), float(i),
- print complex(i)
- print
- for j in list:
- print i + j, i - j, i * j, i / j, i ** j,
- if not (isinstance(i, complex) or
- isinstance(j, complex)):
- print cmp(i, j)
- print
-
-
-if __name__ == '__main__':
- test()
diff --git a/Demo/classes/Rev.py b/Demo/classes/Rev.py
deleted file mode 100755
index 467bd578b7..0000000000
--- a/Demo/classes/Rev.py
+++ /dev/null
@@ -1,89 +0,0 @@
-# A class which presents the reverse of a sequence without duplicating it.
-# From: "Steven D. Majewski"
-
-# It works on mutable or inmutable sequences.
-#
-# >>> for c in Rev( 'Hello World!' ) : sys.stdout.write( c )
-# ... else: sys.stdout.write( '\n' )
-# ...
-# !dlroW olleH
-#
-# The .forw is so you can use anonymous sequences in __init__, and still
-# keep a reference the forward sequence. )
-# If you give it a non-anonymous mutable sequence, the reverse sequence
-# will track the updated values. ( but not reassignment! - another
-# good reason to use anonymous values in creating the sequence to avoid
-# confusion. Maybe it should be change to copy input sequence to break
-# the connection completely ? )
-#
-# >>> nnn = range( 0, 3 )
-# >>> rnn = Rev( nnn )
-# >>> for n in rnn: print n
-# ...
-# 2
-# 1
-# 0
-# >>> for n in range( 4, 6 ): nnn.append( n ) # update nnn
-# ...
-# >>> for n in rnn: print n # prints reversed updated values
-# ...
-# 5
-# 4
-# 2
-# 1
-# 0
-# >>> nnn = nnn[1:-1]
-# >>> nnn
-# [1, 2, 4]
-# >>> for n in rnn: print n # prints reversed values of old nnn
-# ...
-# 5
-# 4
-# 2
-# 1
-# 0
-# >>>
-#
-# WH = Rev( 'Hello World!' )
-# print WH.forw, WH.back
-# nnn = Rev( range( 1, 10 ) )
-# print nnn.forw
-# print nnn
-#
-# produces output:
-#
-# Hello World! !dlroW olleH
-# [1, 2, 3, 4, 5, 6, 7, 8, 9]
-# [9, 8, 7, 6, 5, 4, 3, 2, 1]
-#
-# >>>rrr = Rev( nnn )
-# >>>rrr
-# <1, 2, 3, 4, 5, 6, 7, 8, 9>
-
-from string import joinfields
-class Rev:
- def __init__( self, seq ):
- self.forw = seq
- self.back = self
- def __len__( self ):
- return len( self.forw )
- def __getitem__( self, j ):
- return self.forw[ -( j + 1 ) ]
- def __repr__( self ):
- seq = self.forw
- if type(seq) == type( [] ) :
- wrap = '[]'
- sep = ', '
- elif type(seq) == type( () ) :
- wrap = '()'
- sep = ', '
- elif type(seq) == type( '' ) :
- wrap = ''
- sep = ''
- else:
- wrap = '<>'
- sep = ', '
- outstrs = []
- for item in self.back :
- outstrs.append( str( item ) )
- return wrap[:1] + joinfields( outstrs, sep ) + wrap[-1:]
diff --git a/Demo/classes/Vec.py b/Demo/classes/Vec.py
deleted file mode 100755
index 0a56ddbe1f..0000000000
--- a/Demo/classes/Vec.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# A simple vector class
-
-
-def vec(*v):
- return apply(Vec, v)
-
-
-class Vec:
-
- def __init__(self, *v):
- self.v = []
- for x in v:
- self.v.append(x)
-
-
- def fromlist(self, v):
- self.v = []
- if type(v) <> type([]):
- raise TypeError
- self.v = v[:]
- return self
-
-
- def __repr__(self):
- return 'vec(' + `self.v`[1:-1] + ')'
-
- def __len__(self):
- return len(self.v)
-
- def __getitem__(self, i):
- return self.v[i]
-
- def __add__(a, b):
- # Element-wise addition
- v = []
- for i in range(len(a)):
- v.append(a[i] + b[i])
- return Vec().fromlist(v)
-
- def __sub__(a, b):
- # Element-wise subtraction
- v = []
- for i in range(len(a)):
- v.append(a[i] - b[i])
- return Vec().fromlist(v)
-
- def __mul__(self, scalar):
- # Multiply by scalar
- v = []
- for i in range(len(self.v)):
- v.append(self.v[i]*scalar)
- return Vec().fromlist(v)
-
-
-
-def test():
- a = vec(1, 2, 3)
- b = vec(3, 2, 1)
- print a
- print b
- print a+b
- print a*3.0
-
-test()
diff --git a/Demo/classes/bitvec.py b/Demo/classes/bitvec.py
deleted file mode 100755
index ed89d67666..0000000000
--- a/Demo/classes/bitvec.py
+++ /dev/null
@@ -1,332 +0,0 @@
-#
-# this is a rather strict implementation of a bit vector class
-# it is accessed the same way as an array of python-ints, except
-# the value must be 0 or 1
-#
-
-import sys; rprt = sys.stderr.write #for debugging
-
-error = 'bitvec.error'
-
-
-def _check_value(value):
- if type(value) != type(0) or not 0 <= value < 2:
- raise error, 'bitvec() items must have int value 0 or 1'
-
-
-import math
-
-def _compute_len(param):
- mant, l = math.frexp(float(param))
- bitmask = 1L << l
- if bitmask <= param:
- raise 'FATAL', '(param, l) = ' + `param, l`
- while l:
- bitmask = bitmask >> 1
- if param & bitmask:
- break
- l = l - 1
- return l
-
-
-def _check_key(len, key):
- if type(key) != type(0):
- raise TypeError, 'sequence subscript not int'
- if key < 0:
- key = key + len
- if not 0 <= key < len:
- raise IndexError, 'list index out of range'
- return key
-
-def _check_slice(len, i, j):
- #the type is ok, Python already checked that
- i, j = max(i, 0), min(len, j)
- if i > j:
- i = j
- return i, j
-
-
-class BitVec:
-
- def __init__(self, *params):
- self._data = 0L
- self._len = 0
- if not len(params):
- pass
- elif len(params) == 1:
- param, = params
- if type(param) == type([]):
- value = 0L
- bit_mask = 1L
- for item in param:
- # strict check
- #_check_value(item)
- if item:
- value = value | bit_mask
- bit_mask = bit_mask << 1
- self._data = value
- self._len = len(param)
- elif type(param) == type(0L):
- if param < 0:
- raise error, 'bitvec() can\'t handle negative longs'
- self._data = param
- self._len = _compute_len(param)
- else:
- raise error, 'bitvec() requires array or long parameter'
- elif len(params) == 2:
- param, length = params
- if type(param) == type(0L):
- if param < 0:
- raise error, \
- 'can\'t handle negative longs'
- self._data = param
- if type(length) != type(0):
- raise error, 'bitvec()\'s 2nd parameter must be int'
- computed_length = _compute_len(param)
- if computed_length > length:
- print 'warning: bitvec() value is longer than the length indicates, truncating value'
- self._data = self._data & \
- ((1L << length) - 1)
- self._len = length
- else:
- raise error, 'bitvec() requires array or long parameter'
- else:
- raise error, 'bitvec() requires 0 -- 2 parameter(s)'
-
-
- def append(self, item):
- #_check_value(item)
- #self[self._len:self._len] = [item]
- self[self._len:self._len] = \
- BitVec(long(not not item), 1)
-
-
- def count(self, value):
- #_check_value(value)
- if value:
- data = self._data
- else:
- data = (~self)._data
- count = 0
- while data:
- data, count = data >> 1, count + (data & 1 != 0)
- return count
-
-
- def index(self, value):
- #_check_value(value):
- if value:
- data = self._data
- else:
- data = (~self)._data
- index = 0
- if not data:
- raise ValueError, 'list.index(x): x not in list'
- while not (data & 1):
- data, index = data >> 1, index + 1
- return index
-
-
- def insert(self, index, item):
- #_check_value(item)
- #self[index:index] = [item]
- self[index:index] = BitVec(long(not not item), 1)
-
-
- def remove(self, value):
- del self[self.index(value)]
-
-
- def reverse(self):
- #ouch, this one is expensive!
- #for i in self._len>>1: self[i], self[l-i] = self[l-i], self[i]
- data, result = self._data, 0L
- for i in range(self._len):
- if not data:
- result = result << (self._len - i)
- break
- result, data = (result << 1) | (data & 1), data >> 1
- self._data = result
-
-
- def sort(self):
- c = self.count(1)
- self._data = ((1L << c) - 1) << (self._len - c)
-
-
- def copy(self):
- return BitVec(self._data, self._len)
-
-
- def seq(self):
- result = []
- for i in self:
- result.append(i)
- return result
-
-
- def __repr__(self):
- ##rprt('.' + '__repr__()\n')
- return 'bitvec' + `self._data, self._len`
-
- def __cmp__(self, other, *rest):
- #rprt(`self`+'.__cmp__'+`(other, ) + rest`+'\n')
- if type(other) != type(self):
- other = apply(bitvec, (other, ) + rest)
- #expensive solution... recursive binary, with slicing
- length = self._len
- if length == 0 or other._len == 0:
- return cmp(length, other._len)
- if length != other._len:
- min_length = min(length, other._len)
- return cmp(self[:min_length], other[:min_length]) or \
- cmp(self[min_length:], other[min_length:])
- #the lengths are the same now...
- if self._data == other._data:
- return 0
- if length == 1:
- return cmp(self[0], other[0])
- else:
- length = length >> 1
- return cmp(self[:length], other[:length]) or \
- cmp(self[length:], other[length:])
-
-
- def __len__(self):
- #rprt(`self`+'.__len__()\n')
- return self._len
-
- def __getitem__(self, key):
- #rprt(`self`+'.__getitem__('+`key`+')\n')
- key = _check_key(self._len, key)
- return self._data & (1L << key) != 0
-
- def __setitem__(self, key, value):
- #rprt(`self`+'.__setitem__'+`key, value`+'\n')
- key = _check_key(self._len, key)
- #_check_value(value)
- if value:
- self._data = self._data | (1L << key)
- else:
- self._data = self._data & ~(1L << key)
-
- def __delitem__(self, key):
- #rprt(`self`+'.__delitem__('+`key`+')\n')
- key = _check_key(self._len, key)
- #el cheapo solution...
- self._data = self[:key]._data | self[key+1:]._data >> key
- self._len = self._len - 1
-
- def __getslice__(self, i, j):
- #rprt(`self`+'.__getslice__'+`i, j`+'\n')
- i, j = _check_slice(self._len, i, j)
- if i >= j:
- return BitVec(0L, 0)
- if i:
- ndata = self._data >> i
- else:
- ndata = self._data
- nlength = j - i
- if j != self._len:
- #we'll have to invent faster variants here
- #e.g. mod_2exp
- ndata = ndata & ((1L << nlength) - 1)
- return BitVec(ndata, nlength)
-
- def __setslice__(self, i, j, sequence, *rest):
- #rprt(`self`+'.__setslice__'+`(i, j, sequence) + rest`+'\n')
- i, j = _check_slice(self._len, i, j)
- if type(sequence) != type(self):
- sequence = apply(bitvec, (sequence, ) + rest)
- #sequence is now of our own type
- ls_part = self[:i]
- ms_part = self[j:]
- self._data = ls_part._data | \
- ((sequence._data | \
- (ms_part._data << sequence._len)) << ls_part._len)
- self._len = self._len - j + i + sequence._len
-
- def __delslice__(self, i, j):
- #rprt(`self`+'.__delslice__'+`i, j`+'\n')
- i, j = _check_slice(self._len, i, j)
- if i == 0 and j == self._len:
- self._data, self._len = 0L, 0
- elif i < j:
- self._data = self[:i]._data | (self[j:]._data >> i)
- self._len = self._len - j + i
-
- def __add__(self, other):
- #rprt(`self`+'.__add__('+`other`+')\n')
- retval = self.copy()
- retval[self._len:self._len] = other
- return retval
-
- def __mul__(self, multiplier):
- #rprt(`self`+'.__mul__('+`multiplier`+')\n')
- if type(multiplier) != type(0):
- raise TypeError, 'sequence subscript not int'
- if multiplier <= 0:
- return BitVec(0L, 0)
- elif multiplier == 1:
- return self.copy()
- #handle special cases all 0 or all 1...
- if self._data == 0L:
- return BitVec(0L, self._len * multiplier)
- elif (~self)._data == 0L:
- return ~BitVec(0L, self._len * multiplier)
- #otherwise el cheapo again...
- retval = BitVec(0L, 0)
- while multiplier:
- retval, multiplier = retval + self, multiplier - 1
- return retval
-
- def __and__(self, otherseq, *rest):
- #rprt(`self`+'.__and__'+`(otherseq, ) + rest`+'\n')
- if type(otherseq) != type(self):
- otherseq = apply(bitvec, (otherseq, ) + rest)
- #sequence is now of our own type
- return BitVec(self._data & otherseq._data, \
- min(self._len, otherseq._len))
-
-
- def __xor__(self, otherseq, *rest):
- #rprt(`self`+'.__xor__'+`(otherseq, ) + rest`+'\n')
- if type(otherseq) != type(self):
- otherseq = apply(bitvec, (otherseq, ) + rest)
- #sequence is now of our own type
- return BitVec(self._data ^ otherseq._data, \
- max(self._len, otherseq._len))
-
-
- def __or__(self, otherseq, *rest):
- #rprt(`self`+'.__or__'+`(otherseq, ) + rest`+'\n')
- if type(otherseq) != type(self):
- otherseq = apply(bitvec, (otherseq, ) + rest)
- #sequence is now of our own type
- return BitVec(self._data | otherseq._data, \
- max(self._len, otherseq._len))
-
-
- def __invert__(self):
- #rprt(`self`+'.__invert__()\n')
- return BitVec(~self._data & ((1L << self._len) - 1), \
- self._len)
-
- def __coerce__(self, otherseq, *rest):
- #needed for *some* of the arithmetic operations
- #rprt(`self`+'.__coerce__'+`(otherseq, ) + rest`+'\n')
- if type(otherseq) != type(self):
- otherseq = apply(bitvec, (otherseq, ) + rest)
- return self, otherseq
-
- def __int__(self):
- return int(self._data)
-
- def __long__(self):
- return long(self._data)
-
- def __float__(self):
- return float(self._data)
-
-
-bitvec = BitVec
diff --git a/Demo/comparisons/README b/Demo/comparisons/README
deleted file mode 100644
index 111667c264..0000000000
--- a/Demo/comparisons/README
+++ /dev/null
@@ -1,60 +0,0 @@
-Subject: Re: What language would you use?
-From: Tom Christiansen
-Date: 6 Nov 1994 15:14:51 GMT
-Newsgroups: comp.lang.python,comp.lang.tcl,comp.lang.scheme,comp.lang.misc,comp.lang.perl
-Message-Id: <39irtb$3t4@csnews.cs.Colorado.EDU>
-References: <39b7ha$j9v@zeno.nscf.org> <39hhjp$lgn@csnews.cs.Colorado.EDU> <39hvsu$dus@mathserv.mps.ohio-state.edu>
-
-[...]
-If you're really into benchmarks, I'd love it if someone were to code up
-the following problems in tcl, python, and scheme (and whatever else you'd
-like). Separate versions (one optimized for speed, one for beauty :-) are
-ok. Post your code so we can time it on our own systems.
-
-0) Factorial Test (numerics and function calls)
-
- (we did this already)
-
-1) Regular Expressions Test
-
- Read a file of (extended per egrep) regular expressions (one per line),
- and apply those to all files whose names are listed on the command line.
- Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns
- against a five /etc/termcap files. Tests using more elaborate patters
- would also be interesting. Your code should not break if given hundreds
- of regular expressions or binary files to scan.
-
-2) Sorting Test
-
- Sort an input file that consists of lines like this
-
- var1=23 other=14 ditto=23 fred=2
-
- such that each output line is sorted WRT to the number. Order
- of output lines does not change. Resolve collisions using the
- variable name. e.g.
-
- fred=2 other=14 ditto=23 var1=23
-
- Lines may be up to several kilobytes in length and contain
- zillions of variables.
-
-3) System Test
-
- Given a list of directories, report any bogus symbolic links contained
- anywhere in those subtrees. A bogus symbolic link is one that cannot
- be resolved because it points to a nonexistent or otherwise
- unresolvable file. Do *not* use an external find executable.
- Directories may be very very deep. Print a warning immediately if the
- system you're running on doesn't support symbolic links.
-
-
-I'll post perl solutions if people post the others.
-
-
---tom
---
-Tom Christiansen Perl Consultant, Gamer, Hiker tchrist@mox.perl.com
-
- "But Billy! A *small* allowance prepares you for a lifetime of small
- salaries and for your Social Security payments." --Family Circus
diff --git a/Demo/comparisons/patterns b/Demo/comparisons/patterns
deleted file mode 100755
index f4da846af6..0000000000
--- a/Demo/comparisons/patterns
+++ /dev/null
@@ -1,4 +0,0 @@
-^def
-^class
-^import
-^from
diff --git a/Demo/comparisons/regextest.py b/Demo/comparisons/regextest.py
deleted file mode 100755
index fbc5f6c6eb..0000000000
--- a/Demo/comparisons/regextest.py
+++ /dev/null
@@ -1,46 +0,0 @@
-#! /usr/bin/env python
-
-# 1) Regular Expressions Test
-#
-# Read a file of (extended per egrep) regular expressions (one per line),
-# and apply those to all files whose names are listed on the command line.
-# Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns
-# against a five /etc/termcap files. Tests using more elaborate patters
-# would also be interesting. Your code should not break if given hundreds
-# of regular expressions or binary files to scan.
-
-# This implementation:
-# - combines all patterns into a single one using ( ... | ... | ... )
-# - reads patterns from stdin, scans files given as command line arguments
-# - produces output in the format ::
-# - is only about 2.5 times as slow as egrep (though I couldn't run
-# Tom's test -- this system, a vanilla SGI, only has /etc/terminfo)
-
-import string
-import sys
-import re
-
-def main():
- pats = map(chomp, sys.stdin.readlines())
- bigpat = '(' + '|'.join(pats) + ')'
- prog = re.compile(bigpat)
-
- for file in sys.argv[1:]:
- try:
- fp = open(file, 'r')
- except IOError, msg:
- print "%s: %s" % (file, msg)
- continue
- lineno = 0
- while 1:
- line = fp.readline()
- if not line:
- break
- lineno = lineno + 1
- if prog.search(line):
- print "%s:%s:%s" % (file, lineno, line),
-
-def chomp(s):
- return s.rstrip('\n')
-
-main()
diff --git a/Demo/comparisons/sortingtest.py b/Demo/comparisons/sortingtest.py
deleted file mode 100755
index cabf6260d9..0000000000
--- a/Demo/comparisons/sortingtest.py
+++ /dev/null
@@ -1,51 +0,0 @@
-#! /usr/bin/env python
-
-# 2) Sorting Test
-#
-# Sort an input file that consists of lines like this
-#
-# var1=23 other=14 ditto=23 fred=2
-#
-# such that each output line is sorted WRT to the number. Order
-# of output lines does not change. Resolve collisions using the
-# variable name. e.g.
-#
-# fred=2 other=14 ditto=23 var1=23
-#
-# Lines may be up to several kilobytes in length and contain
-# zillions of variables.
-
-# This implementation:
-# - Reads stdin, writes stdout
-# - Uses any amount of whitespace to separate fields
-# - Allows signed numbers
-# - Treats illegally formatted fields as field=0
-# - Outputs the sorted fields with exactly one space between them
-# - Handles blank input lines correctly
-
-import re
-import string
-import sys
-
-def main():
- prog = re.compile('^(.*)=([-+]?[0-9]+)')
- def makekey(item, prog=prog):
- match = prog.match(item)
- if match:
- var, num = match.group(1, 2)
- return string.atoi(num), var
- else:
- # Bad input -- pretend it's a var with value 0
- return 0, item
- while 1:
- line = sys.stdin.readline()
- if not line:
- break
- items = line.split()
- items = map(makekey, items)
- items.sort()
- for num, var in items:
- print "%s=%s" % (var, num),
- print
-
-main()
diff --git a/Demo/comparisons/systemtest.py b/Demo/comparisons/systemtest.py
deleted file mode 100755
index bbc313ba14..0000000000
--- a/Demo/comparisons/systemtest.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#! /usr/bin/env python
-
-# 3) System Test
-#
-# Given a list of directories, report any bogus symbolic links contained
-# anywhere in those subtrees. A bogus symbolic link is one that cannot
-# be resolved because it points to a nonexistent or otherwise
-# unresolvable file. Do *not* use an external find executable.
-# Directories may be very very deep. Print a warning immediately if the
-# system you're running on doesn't support symbolic links.
-
-# This implementation:
-# - takes one optional argument, using the current directory as default
-# - uses chdir to increase performance
-# - sorts the names per directory
-# - prints output lines of the form "path1 -> path2" as it goes
-# - prints error messages about directories it can't list or chdir into
-
-import os
-import sys
-from stat import *
-
-def main():
- try:
- # Note: can't test for presence of lstat -- it's always there
- dummy = os.readlink
- except AttributeError:
- print "This system doesn't have symbolic links"
- sys.exit(0)
- if sys.argv[1:]:
- prefix = sys.argv[1]
- else:
- prefix = ''
- if prefix:
- os.chdir(prefix)
- if prefix[-1:] != '/': prefix = prefix + '/'
- reportboguslinks(prefix)
- else:
- reportboguslinks('')
-
-def reportboguslinks(prefix):
- try:
- names = os.listdir('.')
- except os.error, msg:
- print "%s%s: can't list: %s" % (prefix, '.', msg)
- return
- names.sort()
- for name in names:
- if name == os.curdir or name == os.pardir:
- continue
- try:
- mode = os.lstat(name)[ST_MODE]
- except os.error:
- print "%s%s: can't stat: %s" % (prefix, name, msg)
- continue
- if S_ISLNK(mode):
- try:
- os.stat(name)
- except os.error:
- print "%s%s -> %s" % \
- (prefix, name, os.readlink(name))
- elif S_ISDIR(mode):
- try:
- os.chdir(name)
- except os.error, msg:
- print "%s%s: can't chdir: %s" % \
- (prefix, name, msg)
- continue
- try:
- reportboguslinks(prefix + name + '/')
- finally:
- os.chdir('..')
-
-main()
diff --git a/Demo/curses/README b/Demo/curses/README
deleted file mode 100644
index f2a3b74499..0000000000
--- a/Demo/curses/README
+++ /dev/null
@@ -1,28 +0,0 @@
-This is a collection of demos and tests for the curses module.
-
-ncurses demos
-=============
-
-These demos are converted from the C versions in the ncurses
-distribution, and were contributed by Thomas Gellekum
-I didn't strive for a `pythonic' style, but bluntly copied the
-originals. I won't attempt to `beautify' the program anytime soon, but
-I wouldn't mind someone else making an effort in that direction, of
-course.
-
-ncurses.py -- currently only a panels demo
- XXX this won't work until panel support is checked in
-rain.py -- raindrops keep falling on my desktop
-tclock.py -- ASCII clock, by Howard Jones
-xmas.py -- I'm dreaming of an ASCII christmas
-
-Please send bugfixes and new contributions to me or, even better,
-submit them to the Python Bug Tracker on SourceForge
-().
-
-
-Other demos
-===========
-
-life.py -- Simple game of Life
-repeat.py -- Repeatedly execute a shell command (like watch(1))
diff --git a/Demo/curses/life.py b/Demo/curses/life.py
deleted file mode 100755
index 4ce09d2f24..0000000000
--- a/Demo/curses/life.py
+++ /dev/null
@@ -1,223 +0,0 @@
-#!/usr/bin/env python
-# life.py -- A curses-based version of Conway's Game of Life.
-# Contributed by AMK
-#
-# An empty board will be displayed, and the following commands are available:
-# E : Erase the board
-# R : Fill the board randomly
-# S : Step for a single generation
-# C : Update continuously until a key is struck
-# Q : Quit
-# Cursor keys : Move the cursor around the board
-# Space or Enter : Toggle the contents of the cursor's position
-#
-# TODO :
-# Support the mouse
-# Use colour if available
-# Make board updates faster
-#
-
-import random, string, traceback
-import curses
-
-class LifeBoard:
- """Encapsulates a Life board
-
- Attributes:
- X,Y : horizontal and vertical size of the board
- state : dictionary mapping (x,y) to 0 or 1
-
- Methods:
- display(update_board) -- If update_board is true, compute the
- next generation. Then display the state
- of the board and refresh the screen.
- erase() -- clear the entire board
- makeRandom() -- fill the board randomly
- set(y,x) -- set the given cell to Live; doesn't refresh the screen
- toggle(y,x) -- change the given cell from live to dead, or vice
- versa, and refresh the screen display
-
- """
- def __init__(self, scr, char=ord('*')):
- """Create a new LifeBoard instance.
-
- scr -- curses screen object to use for display
- char -- character used to render live cells (default: '*')
- """
- self.state={} ; self.scr=scr
- Y, X = self.scr.getmaxyx()
- self.X, self.Y = X-2, Y-2-1
- self.char = char
- self.scr.clear()
-
- # Draw a border around the board
- border_line='+'+(self.X*'-')+'+'
- self.scr.addstr(0, 0, border_line)
- self.scr.addstr(self.Y+1,0, border_line)
- for y in range(0, self.Y):
- self.scr.addstr(1+y, 0, '|')
- self.scr.addstr(1+y, self.X+1, '|')
- self.scr.refresh()
-
- def set(self, y, x):
- """Set a cell to the live state"""
- if x<0 or self.X<=x or y<0 or self.Y<=y:
- raise ValueError, "Coordinates out of range %i,%i"% (y,x)
- self.state[x,y] = 1
-
- def toggle(self, y, x):
- """Toggle a cell's state between live and dead"""
- if x<0 or self.X<=x or y<0 or self.Y<=y:
- raise ValueError, "Coordinates out of range %i,%i"% (y,x)
- if self.state.has_key( (x,y) ):
- del self.state[x,y]
- self.scr.addch(y+1, x+1, ' ')
- else:
- self.state[x,y]=1
- self.scr.addch(y+1, x+1, self.char)
- self.scr.refresh()
-
- def erase(self):
- """Clear the entire board and update the board display"""
- self.state={}
- self.display(update_board=0)
-
- def display(self, update_board=1):
- """Display the whole board, optionally computing one generation"""
- M,N = self.X, self.Y
- if not update_board:
- for i in range(0, M):
- for j in range(0, N):
- if self.state.has_key( (i,j) ):
- self.scr.addch(j+1, i+1, self.char)
- else:
- self.scr.addch(j+1, i+1, ' ')
- self.scr.refresh()
- return
-
- d={} ; self.boring=1
- for i in range(0, M):
- L=range( max(0, i-1), min(M, i+2) )
- for j in range(0, N):
- s=0
- live=self.state.has_key( (i,j) )
- for k in range( max(0, j-1), min(N, j+2) ):
- for l in L:
- if self.state.has_key( (l,k) ):
- s=s+1
- s=s-live
- if s==3:
- # Birth
- d[i,j]=1
- self.scr.addch(j+1, i+1, self.char)
- if not live: self.boring=0
- elif s==2 and live: d[i,j]=1 # Survival
- elif live:
- # Death
- self.scr.addch(j+1, i+1, ' ')
- self.boring=0
- self.state=d
- self.scr.refresh()
-
- def makeRandom(self):
- "Fill the board with a random pattern"
- self.state={}
- for i in range(0, self.X):
- for j in range(0, self.Y):
- if random.random() > 0.5: self.set(j,i)
-
-
-def erase_menu(stdscr, menu_y):
- "Clear the space where the menu resides"
- stdscr.move(menu_y, 0) ; stdscr.clrtoeol()
- stdscr.move(menu_y+1, 0) ; stdscr.clrtoeol()
-
-def display_menu(stdscr, menu_y):
- "Display the menu of possible keystroke commands"
- erase_menu(stdscr, menu_y)
- stdscr.addstr(menu_y, 4,
- 'Use the cursor keys to move, and space or Enter to toggle a cell.')
- stdscr.addstr(menu_y+1, 4,
- 'E)rase the board, R)andom fill, S)tep once or C)ontinuously, Q)uit')
-
-def main(stdscr):
-
- # Clear the screen and display the menu of keys
- stdscr.clear()
- stdscr_y, stdscr_x = stdscr.getmaxyx()
- menu_y=(stdscr_y-3)-1
- display_menu(stdscr, menu_y)
-
- # Allocate a subwindow for the Life board and create the board object
- subwin=stdscr.subwin(stdscr_y-3, stdscr_x, 0, 0)
- board=LifeBoard(subwin, char=ord('*'))
- board.display(update_board=0)
-
- # xpos, ypos are the cursor's position
- xpos, ypos = board.X/2, board.Y/2
-
- # Main loop:
- while (1):
- stdscr.move(1+ypos, 1+xpos) # Move the cursor
- c=stdscr.getch() # Get a keystroke
- if 00: ypos=ypos-1
- elif c==curses.KEY_DOWN and ypos0: xpos=xpos-1
- elif c==curses.KEY_RIGHT and xpos", "LAST"]
-
- stdscr.refresh()
-
- for y in range(0, curses.LINES - 1):
- for x in range(0, curses.COLS):
- stdscr.addstr("%d" % ((y + x) % 10))
- for y in range(0, 1):
- p1 = mkpanel(curses.COLOR_RED,
- curses.LINES / 2 - 2,
- curses.COLS / 8 + 1,
- 0,
- 0)
- p1.set_userptr("p1")
-
- p2 = mkpanel(curses.COLOR_GREEN,
- curses.LINES / 2 + 1,
- curses.COLS / 7,
- curses.LINES / 4,
- curses.COLS / 10)
- p2.set_userptr("p2")
-
- p3 = mkpanel(curses.COLOR_YELLOW,
- curses.LINES / 4,
- curses.COLS / 10,
- curses.LINES / 2,
- curses.COLS / 9)
- p3.set_userptr("p3")
-
- p4 = mkpanel(curses.COLOR_BLUE,
- curses.LINES / 2 - 2,
- curses.COLS / 8,
- curses.LINES / 2 - 2,
- curses.COLS / 3)
- p4.set_userptr("p4")
-
- p5 = mkpanel(curses.COLOR_MAGENTA,
- curses.LINES / 2 - 2,
- curses.COLS / 8,
- curses.LINES / 2,
- curses.COLS / 2 - 2)
- p5.set_userptr("p5")
-
- fill_panel(p1)
- fill_panel(p2)
- fill_panel(p3)
- fill_panel(p4)
- fill_panel(p5)
- p4.hide()
- p5.hide()
- pflush()
- saywhat("press any key to continue")
- wait_a_while()
-
- saywhat("h3 s1 s2 s4 s5;press any key to continue")
- p1.move(0, 0)
- p3.hide()
- p1.show()
- p2.show()
- p4.show()
- p5.show()
- pflush()
- wait_a_while()
-
- saywhat("s1; press any key to continue")
- p1.show()
- pflush()
- wait_a_while()
-
- saywhat("s2; press any key to continue")
- p2.show()
- pflush()
- wait_a_while()
-
- saywhat("m2; press any key to continue")
- p2.move(curses.LINES / 3 + 1, curses.COLS / 8)
- pflush()
- wait_a_while()
-
- saywhat("s3; press any key to continue")
- p3.show()
- pflush()
- wait_a_while()
-
- saywhat("m3; press any key to continue")
- p3.move(curses.LINES / 4 + 1, curses.COLS / 15)
- pflush()
- wait_a_while()
-
- saywhat("b3; press any key to continue")
- p3.bottom()
- pflush()
- wait_a_while()
-
- saywhat("s4; press any key to continue")
- p4.show()
- pflush()
- wait_a_while()
-
- saywhat("s5; press any key to continue")
- p5.show()
- pflush()
- wait_a_while()
-
- saywhat("t3; press any key to continue")
- p3.top()
- pflush()
- wait_a_while()
-
- saywhat("t1; press any key to continue")
- p1.show()
- pflush()
- wait_a_while()
-
- saywhat("t2; press any key to continue")
- p2.show()
- pflush()
- wait_a_while()
-
- saywhat("t3; press any key to continue")
- p3.show()
- pflush()
- wait_a_while()
-
- saywhat("t4; press any key to continue")
- p4.show()
- pflush()
- wait_a_while()
-
- for itmp in range(0, 6):
- w4 = p4.window()
- w5 = p5.window()
-
- saywhat("m4; press any key to continue")
- w4.move(curses.LINES / 8, 1)
- w4.addstr(mod[itmp])
- p4.move(curses.LINES / 6, itmp * curses.COLS / 8)
- w5.move(curses.LINES / 6, 1)
- w5.addstr(mod[itmp])
- pflush()
- wait_a_while()
-
- saywhat("m5; press any key to continue")
- w4.move(curses.LINES / 6, 1)
- w4.addstr(mod[itmp])
- p5.move(curses.LINES / 3 - 1, itmp * 10 + 6)
- w5.move(curses.LINES / 8, 1)
- w5.addstr(mod[itmp])
- pflush()
- wait_a_while()
-
- saywhat("m4; press any key to continue")
- p4.move(curses.LINES / 6, (itmp + 1) * curses.COLS / 8)
- pflush()
- wait_a_while()
-
- saywhat("t5; press any key to continue")
- p5.top()
- pflush()
- wait_a_while()
-
- saywhat("t2; press any key to continue")
- p2.top()
- pflush()
- wait_a_while()
-
- saywhat("t1; press any key to continue")
- p1.top()
- pflush()
- wait_a_while()
-
- saywhat("d2; press any key to continue")
- del p2
- pflush()
- wait_a_while()
-
- saywhat("h3; press any key to continue")
- p3.hide()
- pflush()
- wait_a_while()
-
- saywhat("d1; press any key to continue")
- del p1
- pflush()
- wait_a_while()
-
- saywhat("d4; press any key to continue")
- del p4
- pflush()
- wait_a_while()
-
- saywhat("d5; press any key to continue")
- del p5
- pflush()
- wait_a_while()
- if nap_msec == 1:
- break
- nap_msec = 100
-
-#
-# one fine day there'll be the menu at this place
-#
-curses.wrapper(demo_panels)
diff --git a/Demo/curses/rain.py b/Demo/curses/rain.py
deleted file mode 100644
index 2399d7f438..0000000000
--- a/Demo/curses/rain.py
+++ /dev/null
@@ -1,94 +0,0 @@
-#!/usr/bin/env python
-#
-# $Id$
-#
-# somebody should probably check the randrange()s...
-
-import curses
-from random import randrange
-
-def next_j(j):
- if j == 0:
- j = 4
- else:
- j -= 1
-
- if curses.has_colors():
- z = randrange(0, 3)
- color = curses.color_pair(z)
- if z:
- color = color | curses.A_BOLD
- stdscr.attrset(color)
-
- return j
-
-def main(win):
- # we know that the first argument from curses.wrapper() is stdscr.
- # Initialize it globally for convenience.
- global stdscr
- stdscr = win
-
- if curses.has_colors():
- bg = curses.COLOR_BLACK
- curses.init_pair(1, curses.COLOR_BLUE, bg)
- curses.init_pair(2, curses.COLOR_CYAN, bg)
-
- curses.nl()
- curses.noecho()
- # XXX curs_set() always returns ERR
- # curses.curs_set(0)
- stdscr.timeout(0)
-
- c = curses.COLS - 4
- r = curses.LINES - 4
- xpos = [0] * c
- ypos = [0] * r
- for j in range(4, -1, -1):
- xpos[j] = randrange(0, c) + 2
- ypos[j] = randrange(0, r) + 2
-
- j = 0
- while 1:
- x = randrange(0, c) + 2
- y = randrange(0, r) + 2
-
- stdscr.addch(y, x, ord('.'))
-
- stdscr.addch(ypos[j], xpos[j], ord('o'))
-
- j = next_j(j)
- stdscr.addch(ypos[j], xpos[j], ord('O'))
-
- j = next_j(j)
- stdscr.addch( ypos[j] - 1, xpos[j], ord('-'))
- stdscr.addstr(ypos[j], xpos[j] - 1, "|.|")
- stdscr.addch( ypos[j] + 1, xpos[j], ord('-'))
-
- j = next_j(j)
- stdscr.addch( ypos[j] - 2, xpos[j], ord('-'))
- stdscr.addstr(ypos[j] - 1, xpos[j] - 1, "/ \\")
- stdscr.addstr(ypos[j], xpos[j] - 2, "| O |")
- stdscr.addstr(ypos[j] + 1, xpos[j] - 1, "\\ /")
- stdscr.addch( ypos[j] + 2, xpos[j], ord('-'))
-
- j = next_j(j)
- stdscr.addch( ypos[j] - 2, xpos[j], ord(' '))
- stdscr.addstr(ypos[j] - 1, xpos[j] - 1, " ")
- stdscr.addstr(ypos[j], xpos[j] - 2, " ")
- stdscr.addstr(ypos[j] + 1, xpos[j] - 1, " ")
- stdscr.addch( ypos[j] + 2, xpos[j], ord(' '))
-
- xpos[j] = x
- ypos[j] = y
-
- ch = stdscr.getch()
- if ch == ord('q') or ch == ord('Q'):
- return 0
- elif ch == ord('s'):
- stdscr.nodelay(0)
- elif ch == ord(' '):
- stdscr.nodelay(1)
-
- curses.napms(50)
-
-curses.wrapper(main)
diff --git a/Demo/curses/repeat.py b/Demo/curses/repeat.py
deleted file mode 100755
index 158264cf6b..0000000000
--- a/Demo/curses/repeat.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#! /usr/bin/env python
-
-"""repeat
-
-This simple program repeatedly (with 1-second intervals) executes the
-shell command given on the command line and displays the output (or as
-much of it as fits on the screen). It uses curses to paint each new
-output on top of the old output, so that if nothing changes, the
-screen doesn't change. This is handy to watch for changes in e.g. a
-directory or process listing.
-
-To end, hit Control-C.
-"""
-
-# Author: Guido van Rossum
-
-# Disclaimer: there's a Linux program named 'watch' that does the same
-# thing. Honestly, I didn't know of its existence when I wrote this!
-
-# To do: add features until it has the same functionality as watch(1);
-# then compare code size and development time.
-
-import os
-import sys
-import time
-import curses
-
-def main():
- if not sys.argv[1:]:
- print __doc__
- sys.exit(0)
- cmd = " ".join(sys.argv[1:])
- p = os.popen(cmd, "r")
- text = p.read()
- sts = p.close()
- if sts:
- print >>sys.stderr, "Exit code:", sts
- sys.exit(sts)
- w = curses.initscr()
- try:
- while 1:
- w.erase()
- try:
- w.addstr(text)
- except curses.error:
- pass
- w.refresh()
- time.sleep(1)
- p = os.popen(cmd, "r")
- text = p.read()
- sts = p.close()
- if sts:
- print >>sys.stderr, "Exit code:", sts
- sys.exit(sts)
- finally:
- curses.endwin()
-
-main()
diff --git a/Demo/curses/tclock.py b/Demo/curses/tclock.py
deleted file mode 100644
index f423e9a54b..0000000000
--- a/Demo/curses/tclock.py
+++ /dev/null
@@ -1,146 +0,0 @@
-#!/usr/bin/env python
-#
-# $Id$
-#
-# From tclock.c, Copyright Howard Jones , September 1994.
-
-from math import *
-import curses, time
-
-ASPECT = 2.2
-
-def sign(_x):
- if _x < 0: return -1
- return 1
-
-def A2XY(angle, radius):
- return int(round(ASPECT * radius * sin(angle))), int(round(radius * cos(angle)))
-
-def plot(x, y, col):
- stdscr.addch(y, x, col)
-
-# draw a diagonal line using Bresenham's algorithm
-def dline(pair, from_x, from_y, x2, y2, ch):
- if curses.has_colors():
- stdscr.attrset(curses.color_pair(pair))
-
- dx = x2 - from_x
- dy = y2 - from_y
-
- ax = abs(dx * 2)
- ay = abs(dy * 2)
-
- sx = sign(dx)
- sy = sign(dy)
-
- x = from_x
- y = from_y
-
- if ax > ay:
- d = ay - ax / 2
-
- while 1:
- plot(x, y, ch)
- if x == x2:
- return
-
- if d >= 0:
- y += sy
- d -= ax
- x += sx
- d += ay
- else:
- d = ax - ay / 2
-
- while 1:
- plot(x, y, ch)
- if y == y2:
- return
-
- if d >= 0:
- x += sx
- d -= ay
- y += sy
- d += ax
-
-def main(win):
- global stdscr
- stdscr = win
-
- lastbeep = -1
- my_bg = curses.COLOR_BLACK
-
- stdscr.nodelay(1)
- stdscr.timeout(0)
-# curses.curs_set(0)
- if curses.has_colors():
- curses.init_pair(1, curses.COLOR_RED, my_bg)
- curses.init_pair(2, curses.COLOR_MAGENTA, my_bg)
- curses.init_pair(3, curses.COLOR_GREEN, my_bg)
-
- cx = (curses.COLS - 1) / 2
- cy = curses.LINES / 2
- ch = min( cy-1, int(cx / ASPECT) - 1)
- mradius = (3 * ch) / 4
- hradius = ch / 2
- sradius = 5 * ch / 6
-
- for i in range(0, 12):
- sangle = (i + 1) * 2.0 * pi / 12.0
- sdx, sdy = A2XY(sangle, sradius)
-
- stdscr.addstr(cy - sdy, cx + sdx, "%d" % (i + 1))
-
- stdscr.addstr(0, 0,
- "ASCII Clock by Howard Jones , 1994")
-
- sradius = max(sradius-4, 8)
-
- while 1:
- curses.napms(1000)
-
- tim = time.time()
- t = time.localtime(tim)
-
- hours = t[3] + t[4] / 60.0
- if hours > 12.0:
- hours -= 12.0
-
- mangle = t[4] * 2 * pi / 60.0
- mdx, mdy = A2XY(mangle, mradius)
-
- hangle = hours * 2 * pi / 12.0
- hdx, hdy = A2XY(hangle, hradius)
-
- sangle = t[5] * 2 * pi / 60.0
- sdx, sdy = A2XY(sangle, sradius)
-
- dline(3, cx, cy, cx + mdx, cy - mdy, ord('#'))
-
- stdscr.attrset(curses.A_REVERSE)
- dline(2, cx, cy, cx + hdx, cy - hdy, ord('.'))
- stdscr.attroff(curses.A_REVERSE)
-
- if curses.has_colors():
- stdscr.attrset(curses.color_pair(1))
-
- plot(cx + sdx, cy - sdy, ord('O'))
-
- if curses.has_colors():
- stdscr.attrset(curses.color_pair(0))
-
- stdscr.addstr(curses.LINES - 2, 0, time.ctime(tim))
- stdscr.refresh()
- if (t[5] % 5) == 0 and t[5] != lastbeep:
- lastbeep = t[5]
- curses.beep()
-
- ch = stdscr.getch()
- if ch == ord('q'):
- return 0
-
- plot(cx + sdx, cy - sdy, ord(' '))
- dline(0, cx, cy, cx + hdx, cy - hdy, ord(' '))
- dline(0, cx, cy, cx + mdx, cy - mdy, ord(' '))
-
-curses.wrapper(main)
diff --git a/Demo/curses/xmas.py b/Demo/curses/xmas.py
deleted file mode 100644
index 99c708730d..0000000000
--- a/Demo/curses/xmas.py
+++ /dev/null
@@ -1,906 +0,0 @@
-# asciixmas
-# December 1989 Larry Bartz Indianapolis, IN
-#
-# $Id$
-#
-# I'm dreaming of an ascii character-based monochrome Christmas,
-# Just like the one's I used to know!
-# Via a full duplex communications channel,
-# At 9600 bits per second,
-# Even though it's kinda slow.
-#
-# I'm dreaming of an ascii character-based monochrome Christmas,
-# With ev'ry C program I write!
-# May your screen be merry and bright!
-# And may all your Christmases be amber or green,
-# (for reduced eyestrain and improved visibility)!
-#
-#
-# Notes on the Python version:
-# I used a couple of `try...except curses.error' to get around some functions
-# returning ERR. The errors come from using wrapping functions to fill
-# windows to the last character cell. The C version doesn't have this problem,
-# it simply ignores any return values.
-#
-
-import curses
-import sys
-
-FROMWHO = "Thomas Gellekum "
-
-def set_color(win, color):
- if curses.has_colors():
- n = color + 1
- curses.init_pair(n, color, my_bg)
- win.attroff(curses.A_COLOR)
- win.attron(curses.color_pair(n))
-
-def unset_color(win):
- if curses.has_colors():
- win.attrset(curses.color_pair(0))
-
-def look_out(msecs):
- curses.napms(msecs)
- if stdscr.getch() != -1:
- curses.beep()
- sys.exit(0)
-
-def boxit():
- for y in range(0, 20):
- stdscr.addch(y, 7, ord('|'))
-
- for x in range(8, 80):
- stdscr.addch(19, x, ord('_'))
-
- for x in range(0, 80):
- stdscr.addch(22, x, ord('_'))
-
- return
-
-def seas():
- stdscr.addch(4, 1, ord('S'))
- stdscr.addch(6, 1, ord('E'))
- stdscr.addch(8, 1, ord('A'))
- stdscr.addch(10, 1, ord('S'))
- stdscr.addch(12, 1, ord('O'))
- stdscr.addch(14, 1, ord('N'))
- stdscr.addch(16, 1, ord("'"))
- stdscr.addch(18, 1, ord('S'))
-
- return
-
-def greet():
- stdscr.addch(3, 5, ord('G'))
- stdscr.addch(5, 5, ord('R'))
- stdscr.addch(7, 5, ord('E'))
- stdscr.addch(9, 5, ord('E'))
- stdscr.addch(11, 5, ord('T'))
- stdscr.addch(13, 5, ord('I'))
- stdscr.addch(15, 5, ord('N'))
- stdscr.addch(17, 5, ord('G'))
- stdscr.addch(19, 5, ord('S'))
-
- return
-
-def fromwho():
- stdscr.addstr(21, 13, FROMWHO)
- return
-
-def tree():
- set_color(treescrn, curses.COLOR_GREEN)
- treescrn.addch(1, 11, ord('/'))
- treescrn.addch(2, 11, ord('/'))
- treescrn.addch(3, 10, ord('/'))
- treescrn.addch(4, 9, ord('/'))
- treescrn.addch(5, 9, ord('/'))
- treescrn.addch(6, 8, ord('/'))
- treescrn.addch(7, 7, ord('/'))
- treescrn.addch(8, 6, ord('/'))
- treescrn.addch(9, 6, ord('/'))
- treescrn.addch(10, 5, ord('/'))
- treescrn.addch(11, 3, ord('/'))
- treescrn.addch(12, 2, ord('/'))
-
- treescrn.addch(1, 13, ord('\\'))
- treescrn.addch(2, 13, ord('\\'))
- treescrn.addch(3, 14, ord('\\'))
- treescrn.addch(4, 15, ord('\\'))
- treescrn.addch(5, 15, ord('\\'))
- treescrn.addch(6, 16, ord('\\'))
- treescrn.addch(7, 17, ord('\\'))
- treescrn.addch(8, 18, ord('\\'))
- treescrn.addch(9, 18, ord('\\'))
- treescrn.addch(10, 19, ord('\\'))
- treescrn.addch(11, 21, ord('\\'))
- treescrn.addch(12, 22, ord('\\'))
-
- treescrn.addch(4, 10, ord('_'))
- treescrn.addch(4, 14, ord('_'))
- treescrn.addch(8, 7, ord('_'))
- treescrn.addch(8, 17, ord('_'))
-
- treescrn.addstr(13, 0, "//////////// \\\\\\\\\\\\\\\\\\\\\\\\")
-
- treescrn.addstr(14, 11, "| |")
- treescrn.addstr(15, 11, "|_|")
-
- unset_color(treescrn)
- treescrn.refresh()
- w_del_msg.refresh()
-
- return
-
-def balls():
- treescrn.overlay(treescrn2)
-
- set_color(treescrn2, curses.COLOR_BLUE)
- treescrn2.addch(3, 9, ord('@'))
- treescrn2.addch(3, 15, ord('@'))
- treescrn2.addch(4, 8, ord('@'))
- treescrn2.addch(4, 16, ord('@'))
- treescrn2.addch(5, 7, ord('@'))
- treescrn2.addch(5, 17, ord('@'))
- treescrn2.addch(7, 6, ord('@'))
- treescrn2.addch(7, 18, ord('@'))
- treescrn2.addch(8, 5, ord('@'))
- treescrn2.addch(8, 19, ord('@'))
- treescrn2.addch(10, 4, ord('@'))
- treescrn2.addch(10, 20, ord('@'))
- treescrn2.addch(11, 2, ord('@'))
- treescrn2.addch(11, 22, ord('@'))
- treescrn2.addch(12, 1, ord('@'))
- treescrn2.addch(12, 23, ord('@'))
-
- unset_color(treescrn2)
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def star():
- treescrn2.attrset(curses.A_BOLD | curses.A_BLINK)
- set_color(treescrn2, curses.COLOR_YELLOW)
-
- treescrn2.addch(0, 12, ord('*'))
- treescrn2.standend()
-
- unset_color(treescrn2)
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def strng1():
- treescrn2.attrset(curses.A_BOLD | curses.A_BLINK)
- set_color(treescrn2, curses.COLOR_WHITE)
-
- treescrn2.addch(3, 13, ord('\''))
- treescrn2.addch(3, 12, ord(':'))
- treescrn2.addch(3, 11, ord('.'))
-
- treescrn2.attroff(curses.A_BOLD | curses.A_BLINK)
- unset_color(treescrn2)
-
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def strng2():
- treescrn2.attrset(curses.A_BOLD | curses.A_BLINK)
- set_color(treescrn2, curses.COLOR_WHITE)
-
- treescrn2.addch(5, 14, ord('\''))
- treescrn2.addch(5, 13, ord(':'))
- treescrn2.addch(5, 12, ord('.'))
- treescrn2.addch(5, 11, ord(','))
- treescrn2.addch(6, 10, ord('\''))
- treescrn2.addch(6, 9, ord(':'))
-
- treescrn2.attroff(curses.A_BOLD | curses.A_BLINK)
- unset_color(treescrn2)
-
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def strng3():
- treescrn2.attrset(curses.A_BOLD | curses.A_BLINK)
- set_color(treescrn2, curses.COLOR_WHITE)
-
- treescrn2.addch(7, 16, ord('\''))
- treescrn2.addch(7, 15, ord(':'))
- treescrn2.addch(7, 14, ord('.'))
- treescrn2.addch(7, 13, ord(','))
- treescrn2.addch(8, 12, ord('\''))
- treescrn2.addch(8, 11, ord(':'))
- treescrn2.addch(8, 10, ord('.'))
- treescrn2.addch(8, 9, ord(','))
-
- treescrn2.attroff(curses.A_BOLD | curses.A_BLINK)
- unset_color(treescrn2)
-
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def strng4():
- treescrn2.attrset(curses.A_BOLD | curses.A_BLINK)
- set_color(treescrn2, curses.COLOR_WHITE)
-
- treescrn2.addch(9, 17, ord('\''))
- treescrn2.addch(9, 16, ord(':'))
- treescrn2.addch(9, 15, ord('.'))
- treescrn2.addch(9, 14, ord(','))
- treescrn2.addch(10, 13, ord('\''))
- treescrn2.addch(10, 12, ord(':'))
- treescrn2.addch(10, 11, ord('.'))
- treescrn2.addch(10, 10, ord(','))
- treescrn2.addch(11, 9, ord('\''))
- treescrn2.addch(11, 8, ord(':'))
- treescrn2.addch(11, 7, ord('.'))
- treescrn2.addch(11, 6, ord(','))
- treescrn2.addch(12, 5, ord('\''))
-
- treescrn2.attroff(curses.A_BOLD | curses.A_BLINK)
- unset_color(treescrn2)
-
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def strng5():
- treescrn2.attrset(curses.A_BOLD | curses.A_BLINK)
- set_color(treescrn2, curses.COLOR_WHITE)
-
- treescrn2.addch(11, 19, ord('\''))
- treescrn2.addch(11, 18, ord(':'))
- treescrn2.addch(11, 17, ord('.'))
- treescrn2.addch(11, 16, ord(','))
- treescrn2.addch(12, 15, ord('\''))
- treescrn2.addch(12, 14, ord(':'))
- treescrn2.addch(12, 13, ord('.'))
- treescrn2.addch(12, 12, ord(','))
-
- treescrn2.attroff(curses.A_BOLD | curses.A_BLINK)
- unset_color(treescrn2)
-
- # save a fully lit tree
- treescrn2.overlay(treescrn)
-
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def blinkit():
- treescrn8.touchwin()
-
- for cycle in range(0, 5):
- if cycle == 0:
- treescrn3.overlay(treescrn8)
- treescrn8.refresh()
- w_del_msg.refresh()
- break
- elif cycle == 1:
- treescrn4.overlay(treescrn8)
- treescrn8.refresh()
- w_del_msg.refresh()
- break
- elif cycle == 2:
- treescrn5.overlay(treescrn8)
- treescrn8.refresh()
- w_del_msg.refresh()
- break
- elif cycle == 3:
- treescrn6.overlay(treescrn8)
- treescrn8.refresh()
- w_del_msg.refresh()
- break
- elif cycle == 4:
- treescrn7.overlay(treescrn8)
- treescrn8.refresh()
- w_del_msg.refresh()
- break
-
- treescrn8.touchwin()
-
- # ALL ON
- treescrn.overlay(treescrn8)
- treescrn8.refresh()
- w_del_msg.refresh()
-
- return
-
-def deer_step(win, y, x):
- win.mvwin(y, x)
- win.refresh()
- w_del_msg.refresh()
- look_out(5)
-
-def reindeer():
- y_pos = 0
-
- for x_pos in range(70, 62, -1):
- if x_pos < 66: y_pos = 1
- for looper in range(0, 4):
- dotdeer0.addch(y_pos, x_pos, ord('.'))
- dotdeer0.refresh()
- w_del_msg.refresh()
- dotdeer0.erase()
- dotdeer0.refresh()
- w_del_msg.refresh()
- look_out(50)
-
- y_pos = 2
-
- for x_pos in range(x_pos - 1, 50, -1):
- for looper in range(0, 4):
- if x_pos < 56:
- y_pos = 3
-
- try:
- stardeer0.addch(y_pos, x_pos, ord('*'))
- except curses.error:
- pass
- stardeer0.refresh()
- w_del_msg.refresh()
- stardeer0.erase()
- stardeer0.refresh()
- w_del_msg.refresh()
- else:
- dotdeer0.addch(y_pos, x_pos, ord('*'))
- dotdeer0.refresh()
- w_del_msg.refresh()
- dotdeer0.erase()
- dotdeer0.refresh()
- w_del_msg.refresh()
-
- x_pos = 58
-
- for y_pos in range(2, 5):
- lildeer0.touchwin()
- lildeer0.refresh()
- w_del_msg.refresh()
-
- for looper in range(0, 4):
- deer_step(lildeer3, y_pos, x_pos)
- deer_step(lildeer2, y_pos, x_pos)
- deer_step(lildeer1, y_pos, x_pos)
- deer_step(lildeer2, y_pos, x_pos)
- deer_step(lildeer3, y_pos, x_pos)
-
- lildeer0.touchwin()
- lildeer0.refresh()
- w_del_msg.refresh()
-
- x_pos -= 2
-
- x_pos = 35
-
- for y_pos in range(5, 10):
-
- middeer0.touchwin()
- middeer0.refresh()
- w_del_msg.refresh()
-
- for looper in range(0, 2):
- deer_step(middeer3, y_pos, x_pos)
- deer_step(middeer2, y_pos, x_pos)
- deer_step(middeer1, y_pos, x_pos)
- deer_step(middeer2, y_pos, x_pos)
- deer_step(middeer3, y_pos, x_pos)
-
- middeer0.touchwin()
- middeer0.refresh()
- w_del_msg.refresh()
-
- x_pos -= 3
-
- look_out(300)
-
- y_pos = 1
-
- for x_pos in range(8, 16):
- deer_step(bigdeer4, y_pos, x_pos)
- deer_step(bigdeer3, y_pos, x_pos)
- deer_step(bigdeer2, y_pos, x_pos)
- deer_step(bigdeer1, y_pos, x_pos)
- deer_step(bigdeer2, y_pos, x_pos)
- deer_step(bigdeer3, y_pos, x_pos)
- deer_step(bigdeer4, y_pos, x_pos)
- deer_step(bigdeer0, y_pos, x_pos)
-
- x_pos -= 1
-
- for looper in range(0, 6):
- deer_step(lookdeer4, y_pos, x_pos)
- deer_step(lookdeer3, y_pos, x_pos)
- deer_step(lookdeer2, y_pos, x_pos)
- deer_step(lookdeer1, y_pos, x_pos)
- deer_step(lookdeer2, y_pos, x_pos)
- deer_step(lookdeer3, y_pos, x_pos)
- deer_step(lookdeer4, y_pos, x_pos)
-
- deer_step(lookdeer0, y_pos, x_pos)
-
- for y_pos in range(y_pos, 10):
- for looper in range(0, 2):
- deer_step(bigdeer4, y_pos, x_pos)
- deer_step(bigdeer3, y_pos, x_pos)
- deer_step(bigdeer2, y_pos, x_pos)
- deer_step(bigdeer1, y_pos, x_pos)
- deer_step(bigdeer2, y_pos, x_pos)
- deer_step(bigdeer3, y_pos, x_pos)
- deer_step(bigdeer4, y_pos, x_pos)
- deer_step(bigdeer0, y_pos, x_pos)
-
- y_pos -= 1
-
- deer_step(lookdeer3, y_pos, x_pos)
- return
-
-def main(win):
- global stdscr
- stdscr = win
-
- global my_bg, y_pos, x_pos
- global treescrn, treescrn2, treescrn3, treescrn4
- global treescrn5, treescrn6, treescrn7, treescrn8
- global dotdeer0, stardeer0
- global lildeer0, lildeer1, lildeer2, lildeer3
- global middeer0, middeer1, middeer2, middeer3
- global bigdeer0, bigdeer1, bigdeer2, bigdeer3, bigdeer4
- global lookdeer0, lookdeer1, lookdeer2, lookdeer3, lookdeer4
- global w_holiday, w_del_msg
-
- my_bg = curses.COLOR_BLACK
- # curses.curs_set(0)
-
- treescrn = curses.newwin(16, 27, 3, 53)
- treescrn2 = curses.newwin(16, 27, 3, 53)
- treescrn3 = curses.newwin(16, 27, 3, 53)
- treescrn4 = curses.newwin(16, 27, 3, 53)
- treescrn5 = curses.newwin(16, 27, 3, 53)
- treescrn6 = curses.newwin(16, 27, 3, 53)
- treescrn7 = curses.newwin(16, 27, 3, 53)
- treescrn8 = curses.newwin(16, 27, 3, 53)
-
- dotdeer0 = curses.newwin(3, 71, 0, 8)
-
- stardeer0 = curses.newwin(4, 56, 0, 8)
-
- lildeer0 = curses.newwin(7, 53, 0, 8)
- lildeer1 = curses.newwin(2, 4, 0, 0)
- lildeer2 = curses.newwin(2, 4, 0, 0)
- lildeer3 = curses.newwin(2, 4, 0, 0)
-
- middeer0 = curses.newwin(15, 42, 0, 8)
- middeer1 = curses.newwin(3, 7, 0, 0)
- middeer2 = curses.newwin(3, 7, 0, 0)
- middeer3 = curses.newwin(3, 7, 0, 0)
-
- bigdeer0 = curses.newwin(10, 23, 0, 0)
- bigdeer1 = curses.newwin(10, 23, 0, 0)
- bigdeer2 = curses.newwin(10, 23, 0, 0)
- bigdeer3 = curses.newwin(10, 23, 0, 0)
- bigdeer4 = curses.newwin(10, 23, 0, 0)
-
- lookdeer0 = curses.newwin(10, 25, 0, 0)
- lookdeer1 = curses.newwin(10, 25, 0, 0)
- lookdeer2 = curses.newwin(10, 25, 0, 0)
- lookdeer3 = curses.newwin(10, 25, 0, 0)
- lookdeer4 = curses.newwin(10, 25, 0, 0)
-
- w_holiday = curses.newwin(1, 27, 3, 27)
-
- w_del_msg = curses.newwin(1, 20, 23, 60)
-
- try:
- w_del_msg.addstr(0, 0, "Hit any key to quit")
- except curses.error:
- pass
-
- try:
- w_holiday.addstr(0, 0, "H A P P Y H O L I D A Y S")
- except curses.error:
- pass
-
- # set up the windows for our various reindeer
- lildeer1.addch(0, 0, ord('V'))
- lildeer1.addch(1, 0, ord('@'))
- lildeer1.addch(1, 1, ord('<'))
- lildeer1.addch(1, 2, ord('>'))
- try:
- lildeer1.addch(1, 3, ord('~'))
- except curses.error:
- pass
-
- lildeer2.addch(0, 0, ord('V'))
- lildeer2.addch(1, 0, ord('@'))
- lildeer2.addch(1, 1, ord('|'))
- lildeer2.addch(1, 2, ord('|'))
- try:
- lildeer2.addch(1, 3, ord('~'))
- except curses.error:
- pass
-
- lildeer3.addch(0, 0, ord('V'))
- lildeer3.addch(1, 0, ord('@'))
- lildeer3.addch(1, 1, ord('>'))
- lildeer3.addch(1, 2, ord('<'))
- try:
- lildeer2.addch(1, 3, ord('~')) # XXX
- except curses.error:
- pass
-
- middeer1.addch(0, 2, ord('y'))
- middeer1.addch(0, 3, ord('y'))
- middeer1.addch(1, 2, ord('0'))
- middeer1.addch(1, 3, ord('('))
- middeer1.addch(1, 4, ord('='))
- middeer1.addch(1, 5, ord(')'))
- middeer1.addch(1, 6, ord('~'))
- middeer1.addch(2, 3, ord('\\'))
- middeer1.addch(2, 5, ord('/'))
-
- middeer2.addch(0, 2, ord('y'))
- middeer2.addch(0, 3, ord('y'))
- middeer2.addch(1, 2, ord('0'))
- middeer2.addch(1, 3, ord('('))
- middeer2.addch(1, 4, ord('='))
- middeer2.addch(1, 5, ord(')'))
- middeer2.addch(1, 6, ord('~'))
- middeer2.addch(2, 3, ord('|'))
- middeer2.addch(2, 5, ord('|'))
-
- middeer3.addch(0, 2, ord('y'))
- middeer3.addch(0, 3, ord('y'))
- middeer3.addch(1, 2, ord('0'))
- middeer3.addch(1, 3, ord('('))
- middeer3.addch(1, 4, ord('='))
- middeer3.addch(1, 5, ord(')'))
- middeer3.addch(1, 6, ord('~'))
- middeer3.addch(2, 3, ord('/'))
- middeer3.addch(2, 5, ord('\\'))
-
- bigdeer1.addch(0, 17, ord('\\'))
- bigdeer1.addch(0, 18, ord('/'))
- bigdeer1.addch(0, 19, ord('\\'))
- bigdeer1.addch(0, 20, ord('/'))
- bigdeer1.addch(1, 18, ord('\\'))
- bigdeer1.addch(1, 20, ord('/'))
- bigdeer1.addch(2, 19, ord('|'))
- bigdeer1.addch(2, 20, ord('_'))
- bigdeer1.addch(3, 18, ord('/'))
- bigdeer1.addch(3, 19, ord('^'))
- bigdeer1.addch(3, 20, ord('0'))
- bigdeer1.addch(3, 21, ord('\\'))
- bigdeer1.addch(4, 17, ord('/'))
- bigdeer1.addch(4, 18, ord('/'))
- bigdeer1.addch(4, 19, ord('\\'))
- bigdeer1.addch(4, 22, ord('\\'))
- bigdeer1.addstr(5, 7, "^~~~~~~~~// ~~U")
- bigdeer1.addstr(6, 7, "( \\_____( /") # ))
- bigdeer1.addstr(7, 8, "( ) /")
- bigdeer1.addstr(8, 9, "\\\\ /")
- bigdeer1.addstr(9, 11, "\\>/>")
-
- bigdeer2.addch(0, 17, ord('\\'))
- bigdeer2.addch(0, 18, ord('/'))
- bigdeer2.addch(0, 19, ord('\\'))
- bigdeer2.addch(0, 20, ord('/'))
- bigdeer2.addch(1, 18, ord('\\'))
- bigdeer2.addch(1, 20, ord('/'))
- bigdeer2.addch(2, 19, ord('|'))
- bigdeer2.addch(2, 20, ord('_'))
- bigdeer2.addch(3, 18, ord('/'))
- bigdeer2.addch(3, 19, ord('^'))
- bigdeer2.addch(3, 20, ord('0'))
- bigdeer2.addch(3, 21, ord('\\'))
- bigdeer2.addch(4, 17, ord('/'))
- bigdeer2.addch(4, 18, ord('/'))
- bigdeer2.addch(4, 19, ord('\\'))
- bigdeer2.addch(4, 22, ord('\\'))
- bigdeer2.addstr(5, 7, "^~~~~~~~~// ~~U")
- bigdeer2.addstr(6, 7, "(( )____( /") # ))
- bigdeer2.addstr(7, 7, "( / |")
- bigdeer2.addstr(8, 8, "\\/ |")
- bigdeer2.addstr(9, 9, "|> |>")
-
- bigdeer3.addch(0, 17, ord('\\'))
- bigdeer3.addch(0, 18, ord('/'))
- bigdeer3.addch(0, 19, ord('\\'))
- bigdeer3.addch(0, 20, ord('/'))
- bigdeer3.addch(1, 18, ord('\\'))
- bigdeer3.addch(1, 20, ord('/'))
- bigdeer3.addch(2, 19, ord('|'))
- bigdeer3.addch(2, 20, ord('_'))
- bigdeer3.addch(3, 18, ord('/'))
- bigdeer3.addch(3, 19, ord('^'))
- bigdeer3.addch(3, 20, ord('0'))
- bigdeer3.addch(3, 21, ord('\\'))
- bigdeer3.addch(4, 17, ord('/'))
- bigdeer3.addch(4, 18, ord('/'))
- bigdeer3.addch(4, 19, ord('\\'))
- bigdeer3.addch(4, 22, ord('\\'))
- bigdeer3.addstr(5, 7, "^~~~~~~~~// ~~U")
- bigdeer3.addstr(6, 6, "( ()_____( /") # ))
- bigdeer3.addstr(7, 6, "/ / /")
- bigdeer3.addstr(8, 5, "|/ \\")
- bigdeer3.addstr(9, 5, "/> \\>")
-
- bigdeer4.addch(0, 17, ord('\\'))
- bigdeer4.addch(0, 18, ord('/'))
- bigdeer4.addch(0, 19, ord('\\'))
- bigdeer4.addch(0, 20, ord('/'))
- bigdeer4.addch(1, 18, ord('\\'))
- bigdeer4.addch(1, 20, ord('/'))
- bigdeer4.addch(2, 19, ord('|'))
- bigdeer4.addch(2, 20, ord('_'))
- bigdeer4.addch(3, 18, ord('/'))
- bigdeer4.addch(3, 19, ord('^'))
- bigdeer4.addch(3, 20, ord('0'))
- bigdeer4.addch(3, 21, ord('\\'))
- bigdeer4.addch(4, 17, ord('/'))
- bigdeer4.addch(4, 18, ord('/'))
- bigdeer4.addch(4, 19, ord('\\'))
- bigdeer4.addch(4, 22, ord('\\'))
- bigdeer4.addstr(5, 7, "^~~~~~~~~// ~~U")
- bigdeer4.addstr(6, 6, "( )______( /") # )
- bigdeer4.addstr(7, 5, "(/ \\") # )
- bigdeer4.addstr(8, 0, "v___= ----^")
-
- lookdeer1.addstr(0, 16, "\\/ \\/")
- lookdeer1.addstr(1, 17, "\\Y/ \\Y/")
- lookdeer1.addstr(2, 19, "\\=/")
- lookdeer1.addstr(3, 17, "^\\o o/^")
- lookdeer1.addstr(4, 17, "//( )")
- lookdeer1.addstr(5, 7, "^~~~~~~~~// \\O/")
- lookdeer1.addstr(6, 7, "( \\_____( /") # ))
- lookdeer1.addstr(7, 8, "( ) /")
- lookdeer1.addstr(8, 9, "\\\\ /")
- lookdeer1.addstr(9, 11, "\\>/>")
-
- lookdeer2.addstr(0, 16, "\\/ \\/")
- lookdeer2.addstr(1, 17, "\\Y/ \\Y/")
- lookdeer2.addstr(2, 19, "\\=/")
- lookdeer2.addstr(3, 17, "^\\o o/^")
- lookdeer2.addstr(4, 17, "//( )")
- lookdeer2.addstr(5, 7, "^~~~~~~~~// \\O/")
- lookdeer2.addstr(6, 7, "(( )____( /") # ))
- lookdeer2.addstr(7, 7, "( / |")
- lookdeer2.addstr(8, 8, "\\/ |")
- lookdeer2.addstr(9, 9, "|> |>")
-
- lookdeer3.addstr(0, 16, "\\/ \\/")
- lookdeer3.addstr(1, 17, "\\Y/ \\Y/")
- lookdeer3.addstr(2, 19, "\\=/")
- lookdeer3.addstr(3, 17, "^\\o o/^")
- lookdeer3.addstr(4, 17, "//( )")
- lookdeer3.addstr(5, 7, "^~~~~~~~~// \\O/")
- lookdeer3.addstr(6, 6, "( ()_____( /") # ))
- lookdeer3.addstr(7, 6, "/ / /")
- lookdeer3.addstr(8, 5, "|/ \\")
- lookdeer3.addstr(9, 5, "/> \\>")
-
- lookdeer4.addstr(0, 16, "\\/ \\/")
- lookdeer4.addstr(1, 17, "\\Y/ \\Y/")
- lookdeer4.addstr(2, 19, "\\=/")
- lookdeer4.addstr(3, 17, "^\\o o/^")
- lookdeer4.addstr(4, 17, "//( )")
- lookdeer4.addstr(5, 7, "^~~~~~~~~// \\O/")
- lookdeer4.addstr(6, 6, "( )______( /") # )
- lookdeer4.addstr(7, 5, "(/ \\") # )
- lookdeer4.addstr(8, 0, "v___= ----^")
-
- ###############################################
- curses.cbreak()
- stdscr.nodelay(1)
-
- while 1:
- stdscr.clear()
- treescrn.erase()
- w_del_msg.touchwin()
- treescrn.touchwin()
- treescrn2.erase()
- treescrn2.touchwin()
- treescrn8.erase()
- treescrn8.touchwin()
- stdscr.refresh()
- look_out(150)
- boxit()
- stdscr.refresh()
- look_out(150)
- seas()
- stdscr.refresh()
- greet()
- stdscr.refresh()
- look_out(150)
- fromwho()
- stdscr.refresh()
- look_out(150)
- tree()
- look_out(150)
- balls()
- look_out(150)
- star()
- look_out(150)
- strng1()
- strng2()
- strng3()
- strng4()
- strng5()
-
- # set up the windows for our blinking trees
- #
- # treescrn3
- treescrn.overlay(treescrn3)
-
- # balls
- treescrn3.addch(4, 18, ord(' '))
- treescrn3.addch(7, 6, ord(' '))
- treescrn3.addch(8, 19, ord(' '))
- treescrn3.addch(11, 22, ord(' '))
-
- # star
- treescrn3.addch(0, 12, ord('*'))
-
- # strng1
- treescrn3.addch(3, 11, ord(' '))
-
- # strng2
- treescrn3.addch(5, 13, ord(' '))
- treescrn3.addch(6, 10, ord(' '))
-
- # strng3
- treescrn3.addch(7, 16, ord(' '))
- treescrn3.addch(7, 14, ord(' '))
-
- # strng4
- treescrn3.addch(10, 13, ord(' '))
- treescrn3.addch(10, 10, ord(' '))
- treescrn3.addch(11, 8, ord(' '))
-
- # strng5
- treescrn3.addch(11, 18, ord(' '))
- treescrn3.addch(12, 13, ord(' '))
-
- # treescrn4
- treescrn.overlay(treescrn4)
-
- # balls
- treescrn4.addch(3, 9, ord(' '))
- treescrn4.addch(4, 16, ord(' '))
- treescrn4.addch(7, 6, ord(' '))
- treescrn4.addch(8, 19, ord(' '))
- treescrn4.addch(11, 2, ord(' '))
- treescrn4.addch(12, 23, ord(' '))
-
- # star
- treescrn4.standout()
- treescrn4.addch(0, 12, ord('*'))
- treescrn4.standend()
-
- # strng1
- treescrn4.addch(3, 13, ord(' '))
-
- # strng2
-
- # strng3
- treescrn4.addch(7, 15, ord(' '))
- treescrn4.addch(8, 11, ord(' '))
-
- # strng4
- treescrn4.addch(9, 16, ord(' '))
- treescrn4.addch(10, 12, ord(' '))
- treescrn4.addch(11, 8, ord(' '))
-
- # strng5
- treescrn4.addch(11, 18, ord(' '))
- treescrn4.addch(12, 14, ord(' '))
-
- # treescrn5
- treescrn.overlay(treescrn5)
-
- # balls
- treescrn5.addch(3, 15, ord(' '))
- treescrn5.addch(10, 20, ord(' '))
- treescrn5.addch(12, 1, ord(' '))
-
- # star
- treescrn5.addch(0, 12, ord(' '))
-
- # strng1
- treescrn5.addch(3, 11, ord(' '))
-
- # strng2
- treescrn5.addch(5, 12, ord(' '))
-
- # strng3
- treescrn5.addch(7, 14, ord(' '))
- treescrn5.addch(8, 10, ord(' '))
-
- # strng4
- treescrn5.addch(9, 15, ord(' '))
- treescrn5.addch(10, 11, ord(' '))
- treescrn5.addch(11, 7, ord(' '))
-
- # strng5
- treescrn5.addch(11, 17, ord(' '))
- treescrn5.addch(12, 13, ord(' '))
-
- # treescrn6
- treescrn.overlay(treescrn6)
-
- # balls
- treescrn6.addch(6, 7, ord(' '))
- treescrn6.addch(7, 18, ord(' '))
- treescrn6.addch(10, 4, ord(' '))
- treescrn6.addch(11, 23, ord(' '))
-
- # star
- treescrn6.standout()
- treescrn6.addch(0, 12, ord('*'))
- treescrn6.standend()
-
- # strng1
-
- # strng2
- treescrn6.addch(5, 11, ord(' '))
-
- # strng3
- treescrn6.addch(7, 13, ord(' '))
- treescrn6.addch(8, 9, ord(' '))
-
- # strng4
- treescrn6.addch(9, 14, ord(' '))
- treescrn6.addch(10, 10, ord(' '))
- treescrn6.addch(11, 6, ord(' '))
-
- # strng5
- treescrn6.addch(11, 16, ord(' '))
- treescrn6.addch(12, 12, ord(' '))
-
- # treescrn7
-
- treescrn.overlay(treescrn7)
-
- # balls
- treescrn7.addch(3, 15, ord(' '))
- treescrn7.addch(6, 7, ord(' '))
- treescrn7.addch(7, 18, ord(' '))
- treescrn7.addch(10, 4, ord(' '))
- treescrn7.addch(11, 22, ord(' '))
-
- # star
- treescrn7.addch(0, 12, ord('*'))
-
- # strng1
- treescrn7.addch(3, 12, ord(' '))
-
- # strng2
- treescrn7.addch(5, 13, ord(' '))
- treescrn7.addch(6, 9, ord(' '))
-
- # strng3
- treescrn7.addch(7, 15, ord(' '))
- treescrn7.addch(8, 11, ord(' '))
-
- # strng4
- treescrn7.addch(9, 16, ord(' '))
- treescrn7.addch(10, 12, ord(' '))
- treescrn7.addch(11, 8, ord(' '))
-
- # strng5
- treescrn7.addch(11, 18, ord(' '))
- treescrn7.addch(12, 14, ord(' '))
-
- look_out(150)
- reindeer()
-
- w_holiday.touchwin()
- w_holiday.refresh()
- w_del_msg.refresh()
-
- look_out(500)
- for i in range(0, 20):
- blinkit()
-
-curses.wrapper(main)
diff --git a/Demo/embed/.cvsignore b/Demo/embed/.cvsignore
deleted file mode 100644
index fb98617eb9..0000000000
--- a/Demo/embed/.cvsignore
+++ /dev/null
@@ -1,3 +0,0 @@
-demo
-loop
-importexc
diff --git a/Demo/embed/Makefile b/Demo/embed/Makefile
deleted file mode 100644
index c8d538b608..0000000000
--- a/Demo/embed/Makefile
+++ /dev/null
@@ -1,57 +0,0 @@
-# Makefile for embedded Python use demo.
-# (This version tailored for my Red Hat Linux 6.1 setup;
-# edit lines marked with XXX.)
-
-# XXX The compiler you are using
-CC= gcc
-
-# XXX Top of the build tree and source tree
-blddir= ../..
-srcdir= ../..
-
-# Python version
-VERSION= 2.3
-
-# Compiler flags
-OPT= -g
-INCLUDES= -I$(srcdir)/Include -I$(blddir)
-CFLAGS= $(OPT)
-CPPFLAGS= $(INCLUDES)
-
-# The Python library
-LIBPYTHON= $(blddir)/libpython$(VERSION).a
-
-# XXX edit LIBS (in particular) to match $(blddir)/Modules/Makefile
-LIBS= -lnsl -ldl -lreadline -ltermcap -lieee -lpthread -lutil
-LDFLAGS= -Xlinker -export-dynamic
-SYSLIBS= -lm
-MODLIBS=
-ALLLIBS= $(LIBPYTHON) $(MODLIBS) $(LIBS) $(SYSLIBS)
-
-# Build the demo applications
-all: demo loop importexc
-demo: demo.o
- $(CC) $(LDFLAGS) demo.o $(ALLLIBS) -o demo
-
-loop: loop.o
- $(CC) $(LDFLAGS) loop.o $(ALLLIBS) -o loop
-
-importexc: importexc.o
- $(CC) $(LDFLAGS) importexc.o $(ALLLIBS) -o importexc
-
-# Administrative targets
-
-test: demo
- ./demo
-
-COMMAND="print 'hello world'"
-looptest: loop
- ./loop $(COMMAND)
-
-clean:
- -rm -f *.o core
-
-clobber: clean
- -rm -f *~ @* '#'* demo loop importexc
-
-realclean: clobber
diff --git a/Demo/embed/README b/Demo/embed/README
deleted file mode 100644
index a0f7af8439..0000000000
--- a/Demo/embed/README
+++ /dev/null
@@ -1,19 +0,0 @@
-This directory show how to embed the Python interpreter in your own
-application. The file demo.c shows you all that is needed in your C
-code.
-
-To build it, you may have to edit the Makefile:
-
-1) set blddir to the directory where you built Python, if it isn't in
-the source directory (../..)
-
-2) change the variables that together define the list of libraries
-(MODLIBS, LIBS, SYSLIBS) to link with, to match their definitions in
-$(blddir)/Modules/Makefile
-
-An additional test program, loop.c, is used to experiment with memory
-leakage caused by repeated initialization and finalization of the
-interpreter. It can be build by saying "make loop" and tested with
-"make looptest". Command line usage is "./loop ",
-e.g. "./loop 'print 2+2'" should spit out an endless number of lines
-containing the number 4.
diff --git a/Demo/embed/demo.c b/Demo/embed/demo.c
deleted file mode 100644
index 6005f1396b..0000000000
--- a/Demo/embed/demo.c
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Example of embedding Python in another program */
-
-#include "Python.h"
-
-void initxyzzy(void); /* Forward */
-
-main(int argc, char **argv)
-{
- /* Pass argv[0] to the Python interpreter */
- Py_SetProgramName(argv[0]);
-
- /* Initialize the Python interpreter. Required. */
- Py_Initialize();
-
- /* Add a static module */
- initxyzzy();
-
- /* Define sys.argv. It is up to the application if you
- want this; you can also let it undefined (since the Python
- code is generally not a main program it has no business
- touching sys.argv...) */
- PySys_SetArgv(argc, argv);
-
- /* Do some application specific code */
- printf("Hello, brave new world\n\n");
-
- /* Execute some Python statements (in module __main__) */
- PyRun_SimpleString("import sys\n");
- PyRun_SimpleString("print sys.builtin_module_names\n");
- PyRun_SimpleString("print sys.modules.keys()\n");
- PyRun_SimpleString("print sys.executable\n");
- PyRun_SimpleString("print sys.argv\n");
-
- /* Note that you can call any public function of the Python
- interpreter here, e.g. call_object(). */
-
- /* Some more application specific code */
- printf("\nGoodbye, cruel world\n");
-
- /* Exit, cleaning up the interpreter */
- Py_Exit(0);
- /*NOTREACHED*/
-}
-
-/* A static module */
-
-/* 'self' is not used */
-static PyObject *
-xyzzy_foo(PyObject *self, PyObject* args)
-{
- return PyInt_FromLong(42L);
-}
-
-static PyMethodDef xyzzy_methods[] = {
- {"foo", xyzzy_foo, METH_NOARGS,
- "Return the meaning of everything."},
- {NULL, NULL} /* sentinel */
-};
-
-void
-initxyzzy(void)
-{
- PyImport_AddModule("xyzzy");
- Py_InitModule("xyzzy", xyzzy_methods);
-}
diff --git a/Demo/embed/importexc.c b/Demo/embed/importexc.c
deleted file mode 100644
index 375ce1b686..0000000000
--- a/Demo/embed/importexc.c
+++ /dev/null
@@ -1,17 +0,0 @@
-#include
-
-char* cmd = "import exceptions";
-
-int main()
-{
- Py_Initialize();
- PyEval_InitThreads();
- PyRun_SimpleString(cmd);
- Py_EndInterpreter(PyThreadState_Get());
-
- Py_NewInterpreter();
- PyRun_SimpleString(cmd);
- Py_Finalize();
-
- return 0;
-}
diff --git a/Demo/embed/loop.c b/Demo/embed/loop.c
deleted file mode 100644
index d5af82986d..0000000000
--- a/Demo/embed/loop.c
+++ /dev/null
@@ -1,33 +0,0 @@
-/* Simple program that repeatedly calls Py_Initialize(), does something, and
- then calls Py_Finalize(). This should help finding leaks related to
- initialization. */
-
-#include "Python.h"
-
-main(int argc, char **argv)
-{
- int count = -1;
- char *command;
-
- if (argc < 2 || argc > 3) {
- fprintf(stderr, "usage: loop [count]\n");
- exit(2);
- }
- command = argv[1];
-
- if (argc == 3) {
- count = atoi(argv[2]);
- }
-
- Py_SetProgramName(argv[0]);
-
- /* uncomment this if you don't want to load site.py */
- /* Py_NoSiteFlag = 1; */
-
- while (count == -1 || --count >= 0 ) {
- Py_Initialize();
- PyRun_SimpleString(command);
- Py_Finalize();
- }
- return 0;
-}
diff --git a/Demo/imputil/importers.py b/Demo/imputil/importers.py
deleted file mode 100644
index 864ff02f52..0000000000
--- a/Demo/imputil/importers.py
+++ /dev/null
@@ -1,248 +0,0 @@
-#
-# importers.py
-#
-# Demonstration subclasses of imputil.Importer
-#
-
-# There should be consideration for the imports below if it is desirable
-# to have "all" modules be imported through the imputil system.
-
-# these are C extensions
-import sys
-import imp
-import struct
-import marshal
-
-# these are .py modules
-import imputil
-import os
-
-######################################################################
-
-_TupleType = type(())
-_StringType = type('')
-
-######################################################################
-
-# byte-compiled file suffic character
-_suffix_char = __debug__ and 'c' or 'o'
-
-# byte-compiled file suffix
-_suffix = '.py' + _suffix_char
-
-# the C_EXTENSION suffixes
-_c_suffixes = filter(lambda x: x[2] == imp.C_EXTENSION, imp.get_suffixes())
-
-def _timestamp(pathname):
- "Return the file modification time as a Long."
- try:
- s = os.stat(pathname)
- except OSError:
- return None
- return long(s[8])
-
-def _fs_import(dir, modname, fqname):
- "Fetch a module from the filesystem."
-
- pathname = os.path.join(dir, modname)
- if os.path.isdir(pathname):
- values = { '__pkgdir__' : pathname, '__path__' : [ pathname ] }
- ispkg = 1
- pathname = os.path.join(pathname, '__init__')
- else:
- values = { }
- ispkg = 0
-
- # look for dynload modules
- for desc in _c_suffixes:
- file = pathname + desc[0]
- try:
- fp = open(file, desc[1])
- except IOError:
- pass
- else:
- module = imp.load_module(fqname, fp, file, desc)
- values['__file__'] = file
- return 0, module, values
-
- t_py = _timestamp(pathname + '.py')
- t_pyc = _timestamp(pathname + _suffix)
- if t_py is None and t_pyc is None:
- return None
- code = None
- if t_py is None or (t_pyc is not None and t_pyc >= t_py):
- file = pathname + _suffix
- f = open(file, 'rb')
- if f.read(4) == imp.get_magic():
- t = struct.unpack('., where
- can be located using a subclass-specific mechanism and the
- is found in the archive using a subclass-specific mechanism.
-
- This class defines two hooks for subclasses: one to locate an archive
- (and possibly return some context for future subfile lookups), and one
- to locate subfiles.
- """
-
- def get_code(self, parent, modname, fqname):
- if parent:
- # the Importer._finish_import logic ensures that we handle imports
- # under the top level module (package / archive).
- assert parent.__importer__ == self
-
- # if a parent "package" is provided, then we are importing a
- # sub-file from the archive.
- result = self.get_subfile(parent.__archive__, modname)
- if result is None:
- return None
- if isinstance(result, _TupleType):
- assert len(result) == 2
- return (0,) + result
- return 0, result, {}
-
- # no parent was provided, so the archive should exist somewhere on the
- # default "path".
- archive = self.get_archive(modname)
- if archive is None:
- return None
- return 1, "", {'__archive__':archive}
-
- def get_archive(self, modname):
- """Get an archive of modules.
-
- This method should locate an archive and return a value which can be
- used by get_subfile to load modules from it. The value may be a simple
- pathname, an open file, or a complex object that caches information
- for future imports.
-
- Return None if the archive was not found.
- """
- raise RuntimeError, "get_archive not implemented"
-
- def get_subfile(self, archive, modname):
- """Get code from a subfile in the specified archive.
-
- Given the specified archive (as returned by get_archive()), locate
- and return a code object for the specified module name.
-
- A 2-tuple may be returned, consisting of a code object and a dict
- of name/values to place into the target module.
-
- Return None if the subfile was not found.
- """
- raise RuntimeError, "get_subfile not implemented"
-
-
-class PackageArchive(PackageArchiveImporter):
- "PackageArchiveImporter subclass that refers to a specific archive."
-
- def __init__(self, modname, archive_pathname):
- self.__modname = modname
- self.__path = archive_pathname
-
- def get_archive(self, modname):
- if modname == self.__modname:
- return self.__path
- return None
-
- # get_subfile is passed the full pathname of the archive
-
-
-######################################################################
-#
-# Emulate the standard directory-based import mechanism
-#
-class DirectoryImporter(imputil.Importer):
- "Importer subclass to emulate the standard importer."
-
- def __init__(self, dir):
- self.dir = dir
-
- def get_code(self, parent, modname, fqname):
- if parent:
- dir = parent.__pkgdir__
- else:
- dir = self.dir
-
- # Return the module (and other info) if found in the specified
- # directory. Otherwise, return None.
- return _fs_import(dir, modname, fqname)
-
- def __repr__(self):
- return '<%s.%s for "%s" at 0x%x>' % (self.__class__.__module__,
- self.__class__.__name__,
- self.dir,
- id(self))
-
-
-######################################################################
-#
-# Emulate the standard path-style import mechanism
-#
-class PathImporter(imputil.Importer):
- def __init__(self, path=sys.path):
- self.path = path
-
- def get_code(self, parent, modname, fqname):
- if parent:
- # we are looking for a module inside of a specific package
- return _fs_import(parent.__pkgdir__, modname, fqname)
-
- # scan sys.path, looking for the requested module
- for dir in self.path:
- if isinstance(dir, _StringType):
- result = _fs_import(dir, modname, fqname)
- if result:
- return result
-
- # not found
- return None
-
-######################################################################
-
-def _test_dir():
- "Debug/test function to create DirectoryImporters from sys.path."
- imputil.ImportManager().install()
- path = sys.path[:]
- path.reverse()
- for d in path:
- sys.path.insert(0, DirectoryImporter(d))
- sys.path.insert(0, imputil.BuiltinImporter())
-
-def _test_revamp():
- "Debug/test function for the revamped import system."
- imputil.ImportManager().install()
- sys.path.insert(0, PathImporter())
- sys.path.insert(0, imputil.BuiltinImporter())
diff --git a/Demo/imputil/knee.py b/Demo/imputil/knee.py
deleted file mode 100644
index 64764da04d..0000000000
--- a/Demo/imputil/knee.py
+++ /dev/null
@@ -1,126 +0,0 @@
-"""An Python re-implementation of hierarchical module import.
-
-This code is intended to be read, not executed. However, it does work
--- all you need to do to enable it is "import knee".
-
-(The name is a pun on the klunkier predecessor of this module, "ni".)
-
-"""
-
-import sys, imp, __builtin__
-
-
-# Replacement for __import__()
-def import_hook(name, globals=None, locals=None, fromlist=None):
- parent = determine_parent(globals)
- q, tail = find_head_package(parent, name)
- m = load_tail(q, tail)
- if not fromlist:
- return q
- if hasattr(m, "__path__"):
- ensure_fromlist(m, fromlist)
- return m
-
-def determine_parent(globals):
- if not globals or not globals.has_key("__name__"):
- return None
- pname = globals['__name__']
- if globals.has_key("__path__"):
- parent = sys.modules[pname]
- assert globals is parent.__dict__
- return parent
- if '.' in pname:
- i = pname.rfind('.')
- pname = pname[:i]
- parent = sys.modules[pname]
- assert parent.__name__ == pname
- return parent
- return None
-
-def find_head_package(parent, name):
- if '.' in name:
- i = name.find('.')
- head = name[:i]
- tail = name[i+1:]
- else:
- head = name
- tail = ""
- if parent:
- qname = "%s.%s" % (parent.__name__, head)
- else:
- qname = head
- q = import_module(head, qname, parent)
- if q: return q, tail
- if parent:
- qname = head
- parent = None
- q = import_module(head, qname, parent)
- if q: return q, tail
- raise ImportError, "No module named " + qname
-
-def load_tail(q, tail):
- m = q
- while tail:
- i = tail.find('.')
- if i < 0: i = len(tail)
- head, tail = tail[:i], tail[i+1:]
- mname = "%s.%s" % (m.__name__, head)
- m = import_module(head, mname, m)
- if not m:
- raise ImportError, "No module named " + mname
- return m
-
-def ensure_fromlist(m, fromlist, recursive=0):
- for sub in fromlist:
- if sub == "*":
- if not recursive:
- try:
- all = m.__all__
- except AttributeError:
- pass
- else:
- ensure_fromlist(m, all, 1)
- continue
- if sub != "*" and not hasattr(m, sub):
- subname = "%s.%s" % (m.__name__, sub)
- submod = import_module(sub, subname, m)
- if not submod:
- raise ImportError, "No module named " + subname
-
-def import_module(partname, fqname, parent):
- try:
- return sys.modules[fqname]
- except KeyError:
- pass
- try:
- fp, pathname, stuff = imp.find_module(partname,
- parent and parent.__path__)
- except ImportError:
- return None
- try:
- m = imp.load_module(fqname, fp, pathname, stuff)
- finally:
- if fp: fp.close()
- if parent:
- setattr(parent, partname, m)
- return m
-
-
-# Replacement for reload()
-def reload_hook(module):
- name = module.__name__
- if '.' not in name:
- return import_module(name, name, None)
- i = name.rfind('.')
- pname = name[:i]
- parent = sys.modules[pname]
- return import_module(name[i+1:], name, parent)
-
-
-# Save the original hooks
-original_import = __builtin__.__import__
-original_reload = __builtin__.reload
-
-# Now install our hooks
-__builtin__.__import__ = import_hook
-__builtin__.reload = reload_hook
diff --git a/Demo/md5test/README b/Demo/md5test/README
deleted file mode 100644
index be7621e464..0000000000
--- a/Demo/md5test/README
+++ /dev/null
@@ -1,10 +0,0 @@
-This is the Python version of the MD5 test program from the MD5
-Internet Draft (Rivest and Dusse, The MD5 Message-Digest Algorithm, 10
-July 1991). The file "foo" contains the string "abc" with no trailing
-newline.
-
-When called without arguments, it acts as a filter. When called with
-"-x", it executes a self-test, and the output should literally match
-the output given in the RFC.
-
-Code by Jan-Hein B\"uhrman after the original in C.
diff --git a/Demo/md5test/foo b/Demo/md5test/foo
deleted file mode 100755
index f2ba8f84ab..0000000000
--- a/Demo/md5test/foo
+++ /dev/null
@@ -1 +0,0 @@
-abc
\ No newline at end of file
diff --git a/Demo/md5test/md5driver.py b/Demo/md5test/md5driver.py
deleted file mode 100755
index bbd613047a..0000000000
--- a/Demo/md5test/md5driver.py
+++ /dev/null
@@ -1,123 +0,0 @@
-import string
-import md5
-from sys import argv
-
-def MDPrint(str):
- outstr = ''
- for i in str:
- o = ord(i)
- outstr = (outstr
- + string.hexdigits[(o >> 4) & 0xF]
- + string.hexdigits[o & 0xF])
- print outstr,
-
-
-from time import time
-
-def makestr(start, end):
- result = ''
- for i in range(start, end + 1):
- result = result + chr(i)
-
- return result
-
-
-def MDTimeTrial():
- TEST_BLOCK_SIZE = 1000
- TEST_BLOCKS = 10000
-
- TEST_BYTES = TEST_BLOCK_SIZE * TEST_BLOCKS
-
- # initialize test data, need temporary string filler
-
- filsiz = 1 << 8
- filler = makestr(0, filsiz-1)
- data = filler * (TEST_BLOCK_SIZE / filsiz);
- data = data + filler[:(TEST_BLOCK_SIZE % filsiz)]
-
- del filsiz, filler
-
-
- # start timer
- print 'MD5 time trial. Processing', TEST_BYTES, 'characters...'
- t1 = time()
-
- mdContext = md5.new()
-
- for i in range(TEST_BLOCKS):
- mdContext.update(data)
-
- str = mdContext.digest()
- t2 = time()
-
- MDPrint(str)
- print 'is digest of test input.'
- print 'Seconds to process test input:', t2 - t1
- print 'Characters processed per second:', TEST_BYTES / (t2 - t1)
-
-
-def MDString(str):
- MDPrint(md5.new(str).digest())
- print '"' + str + '"'
-
-
-def MDFile(filename):
- f = open(filename, 'rb');
- mdContext = md5.new()
-
- while 1:
- data = f.read(1024)
- if not data:
- break
- mdContext.update(data)
-
- MDPrint(mdContext.digest())
- print filename
-
-
-import sys
-
-def MDFilter():
- mdContext = md5.new()
-
- while 1:
- data = sys.stdin.read(16)
- if not data:
- break
- mdContext.update(data)
-
- MDPrint(mdContext.digest())
- print
-
-
-def MDTestSuite():
- print 'MD5 test suite results:'
- MDString('')
- MDString('a')
- MDString('abc')
- MDString('message digest')
- MDString(makestr(ord('a'), ord('z')))
- MDString(makestr(ord('A'), ord('Z'))
- + makestr(ord('a'), ord('z'))
- + makestr(ord('0'), ord('9')))
- MDString((makestr(ord('1'), ord('9')) + '0') * 8)
-
- # Contents of file foo are "abc"
- MDFile('foo')
-
-
-# I don't wanna use getopt(), since I want to use the same i/f...
-def main():
- if len(argv) == 1:
- MDFilter()
- for arg in argv[1:]:
- if arg[:2] == '-s':
- MDString(arg[2:])
- elif arg == '-t':
- MDTimeTrial()
- elif arg == '-x':
- MDTestSuite()
- else:
- MDFile(arg)
-
-main()
diff --git a/Demo/metaclasses/Eiffel.py b/Demo/metaclasses/Eiffel.py
deleted file mode 100644
index 68eb1cd21d..0000000000
--- a/Demo/metaclasses/Eiffel.py
+++ /dev/null
@@ -1,113 +0,0 @@
-"""Support Eiffel-style preconditions and postconditions.
-
-For example,
-
-class C:
- def m1(self, arg):
- require arg > 0
- return whatever
- ensure Result > arg
-
-can be written (clumsily, I agree) as:
-
-class C(Eiffel):
- def m1(self, arg):
- return whatever
- def m1_pre(self, arg):
- assert arg > 0
- def m1_post(self, Result, arg):
- assert Result > arg
-
-Pre- and post-conditions for a method, being implemented as methods
-themselves, are inherited independently from the method. This gives
-much of the same effect of Eiffel, where pre- and post-conditions are
-inherited when a method is overridden by a derived class. However,
-when a derived class in Python needs to extend a pre- or
-post-condition, it must manually merge the base class' pre- or
-post-condition with that defined in the derived class', for example:
-
-class D(C):
- def m1(self, arg):
- return arg**2
- def m1_post(self, Result, arg):
- C.m1_post(self, Result, arg)
- assert Result < 100
-
-This gives derived classes more freedom but also more responsibility
-than in Eiffel, where the compiler automatically takes care of this.
-
-In Eiffel, pre-conditions combine using contravariance, meaning a
-derived class can only make a pre-condition weaker; in Python, this is
-up to the derived class. For example, a derived class that takes away
-the requirement that arg > 0 could write:
-
- def m1_pre(self, arg):
- pass
-
-but one could equally write a derived class that makes a stronger
-requirement:
-
- def m1_pre(self, arg):
- require arg > 50
-
-It would be easy to modify the classes shown here so that pre- and
-post-conditions can be disabled (separately, on a per-class basis).
-
-A different design would have the pre- or post-condition testing
-functions return true for success and false for failure. This would
-make it possible to implement automatic combination of inherited
-and new pre-/post-conditions. All this is left as an exercise to the
-reader.
-
-"""
-
-from Meta import MetaClass, MetaHelper, MetaMethodWrapper
-
-class EiffelMethodWrapper(MetaMethodWrapper):
-
- def __init__(self, func, inst):
- MetaMethodWrapper.__init__(self, func, inst)
- # Note that the following causes recursive wrappers around
- # the pre-/post-condition testing methods. These are harmless
- # but inefficient; to avoid them, the lookup must be done
- # using the class.
- try:
- self.pre = getattr(inst, self.__name__ + "_pre")
- except AttributeError:
- self.pre = None
- try:
- self.post = getattr(inst, self.__name__ + "_post")
- except AttributeError:
- self.post = None
-
- def __call__(self, *args, **kw):
- if self.pre:
- apply(self.pre, args, kw)
- Result = apply(self.func, (self.inst,) + args, kw)
- if self.post:
- apply(self.post, (Result,) + args, kw)
- return Result
-
-class EiffelHelper(MetaHelper):
- __methodwrapper__ = EiffelMethodWrapper
-
-class EiffelMetaClass(MetaClass):
- __helper__ = EiffelHelper
-
-Eiffel = EiffelMetaClass('Eiffel', (), {})
-
-
-def _test():
- class C(Eiffel):
- def m1(self, arg):
- return arg+1
- def m1_pre(self, arg):
- assert arg > 0, "precondition for m1 failed"
- def m1_post(self, Result, arg):
- assert Result > arg
- x = C()
- x.m1(12)
-## x.m1(-1)
-
-if __name__ == '__main__':
- _test()
diff --git a/Demo/metaclasses/Enum.py b/Demo/metaclasses/Enum.py
deleted file mode 100644
index 13a3ed7d6d..0000000000
--- a/Demo/metaclasses/Enum.py
+++ /dev/null
@@ -1,169 +0,0 @@
-"""Enumeration metaclass.
-
-XXX This is very much a work in progress.
-
-"""
-
-import string
-
-class EnumMetaClass:
- """Metaclass for enumeration.
-
- To define your own enumeration, do something like
-
- class Color(Enum):
- red = 1
- green = 2
- blue = 3
-
- Now, Color.red, Color.green and Color.blue behave totally
- different: they are enumerated values, not integers.
-
- Enumerations cannot be instantiated; however they can be
- subclassed.
-
- """
-
- def __init__(self, name, bases, dict):
- """Constructor -- create an enumeration.
-
- Called at the end of the class statement. The arguments are
- the name of the new class, a tuple containing the base
- classes, and a dictionary containing everything that was
- entered in the class' namespace during execution of the class
- statement. In the above example, it would be {'red': 1,
- 'green': 2, 'blue': 3}.
-
- """
- for base in bases:
- if base.__class__ is not EnumMetaClass:
- raise TypeError, "Enumeration base class must be enumeration"
- bases = filter(lambda x: x is not Enum, bases)
- self.__name__ = name
- self.__bases__ = bases
- self.__dict = {}
- for key, value in dict.items():
- self.__dict[key] = EnumInstance(name, key, value)
-
- def __getattr__(self, name):
- """Return an enumeration value.
-
- For example, Color.red returns the value corresponding to red.
-
- XXX Perhaps the values should be created in the constructor?
-
- This looks in the class dictionary and if it is not found
- there asks the base classes.
-
- The special attribute __members__ returns the list of names
- defined in this class (it does not merge in the names defined
- in base classes).
-
- """
- if name == '__members__':
- return self.__dict.keys()
-
- try:
- return self.__dict[name]
- except KeyError:
- for base in self.__bases__:
- try:
- return getattr(base, name)
- except AttributeError:
- continue
-
- raise AttributeError, name
-
- def __repr__(self):
- s = self.__name__
- if self.__bases__:
- s = s + '(' + string.join(map(lambda x: x.__name__,
- self.__bases__), ", ") + ')'
- if self.__dict:
- list = []
- for key, value in self.__dict.items():
- list.append("%s: %s" % (key, int(value)))
- s = "%s: {%s}" % (s, string.join(list, ", "))
- return s
-
-
-class EnumInstance:
- """Class to represent an enumeration value.
-
- EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves
- like the integer 12 when compared, but doesn't support arithmetic.
-
- XXX Should it record the actual enumeration rather than just its
- name?
-
- """
-
- def __init__(self, classname, enumname, value):
- self.__classname = classname
- self.__enumname = enumname
- self.__value = value
-
- def __int__(self):
- return self.__value
-
- def __repr__(self):
- return "EnumInstance(%s, %s, %s)" % (`self.__classname`,
- `self.__enumname`,
- `self.__value`)
-
- def __str__(self):
- return "%s.%s" % (self.__classname, self.__enumname)
-
- def __cmp__(self, other):
- return cmp(self.__value, int(other))
-
-
-# Create the base class for enumerations.
-# It is an empty enumeration.
-Enum = EnumMetaClass("Enum", (), {})
-
-
-def _test():
-
- class Color(Enum):
- red = 1
- green = 2
- blue = 3
-
- print Color.red
- print dir(Color)
-
- print Color.red == Color.red
- print Color.red == Color.blue
- print Color.red == 1
- print Color.red == 2
-
- class ExtendedColor(Color):
- white = 0
- orange = 4
- yellow = 5
- purple = 6
- black = 7
-
- print ExtendedColor.orange
- print ExtendedColor.red
-
- print Color.red == ExtendedColor.red
-
- class OtherColor(Enum):
- white = 4
- blue = 5
-
- class MergedColor(Color, OtherColor):
- pass
-
- print MergedColor.red
- print MergedColor.white
-
- print Color
- print ExtendedColor
- print OtherColor
- print MergedColor
-
-if __name__ == '__main__':
- _test()
diff --git a/Demo/metaclasses/Meta.py b/Demo/metaclasses/Meta.py
deleted file mode 100644
index 39cbef6266..0000000000
--- a/Demo/metaclasses/Meta.py
+++ /dev/null
@@ -1,120 +0,0 @@
-"""Generic metaclass.
-
-XXX This is very much a work in progress.
-
-"""
-
-import types
-
-class MetaMethodWrapper:
-
- def __init__(self, func, inst):
- self.func = func
- self.inst = inst
- self.__name__ = self.func.__name__
-
- def __call__(self, *args, **kw):
- return apply(self.func, (self.inst,) + args, kw)
-
-class MetaHelper:
-
- __methodwrapper__ = MetaMethodWrapper # For derived helpers to override
-
- def __helperinit__(self, formalclass):
- self.__formalclass__ = formalclass
-
- def __getattr__(self, name):
- # Invoked for any attr not in the instance's __dict__
- try:
- raw = self.__formalclass__.__getattr__(name)
- except AttributeError:
- try:
- ga = self.__formalclass__.__getattr__('__usergetattr__')
- except (KeyError, AttributeError):
- raise AttributeError, name
- return ga(self, name)
- if type(raw) != types.FunctionType:
- return raw
- return self.__methodwrapper__(raw, self)
-
-class MetaClass:
-
- """A generic metaclass.
-
- This can be subclassed to implement various kinds of meta-behavior.
-
- """
-
- __helper__ = MetaHelper # For derived metaclasses to override
-
- __inited = 0
-
- def __init__(self, name, bases, dict):
- try:
- ga = dict['__getattr__']
- except KeyError:
- pass
- else:
- dict['__usergetattr__'] = ga
- del dict['__getattr__']
- self.__name__ = name
- self.__bases__ = bases
- self.__realdict__ = dict
- self.__inited = 1
-
- def __getattr__(self, name):
- try:
- return self.__realdict__[name]
- except KeyError:
- for base in self.__bases__:
- try:
- return base.__getattr__(name)
- except AttributeError:
- pass
- raise AttributeError, name
-
- def __setattr__(self, name, value):
- if not self.__inited:
- self.__dict__[name] = value
- else:
- self.__realdict__[name] = value
-
- def __call__(self, *args, **kw):
- inst = self.__helper__()
- inst.__helperinit__(self)
- try:
- init = inst.__getattr__('__init__')
- except AttributeError:
- init = lambda: None
- apply(init, args, kw)
- return inst
-
-
-Meta = MetaClass('Meta', (), {})
-
-
-def _test():
- class C(Meta):
- def __init__(self, *args):
- print "__init__, args =", args
- def m1(self, x):
- print "m1(x=%s)" %`x`
- print C
- x = C()
- print x
- x.m1(12)
- class D(C):
- def __getattr__(self, name):
- if name[:2] == '__': raise AttributeError, name
- return "getattr:%s" % name
- x = D()
- print x.foo
- print x._foo
-## print x.__foo
-## print x.__foo__
-
-
-if __name__ == '__main__':
- _test()
-
-
diff --git a/Demo/metaclasses/Simple.py b/Demo/metaclasses/Simple.py
deleted file mode 100644
index 03ed2592ee..0000000000
--- a/Demo/metaclasses/Simple.py
+++ /dev/null
@@ -1,45 +0,0 @@
-import types
-
-class Tracing:
- def __init__(self, name, bases, namespace):
- """Create a new class."""
- self.__name__ = name
- self.__bases__ = bases
- self.__namespace__ = namespace
- def __call__(self):
- """Create a new instance."""
- return Instance(self)
-
-class Instance:
- def __init__(self, klass):
- self.__klass__ = klass
- def __getattr__(self, name):
- try:
- value = self.__klass__.__namespace__[name]
- except KeyError:
- raise AttributeError, name
- if type(value) is not types.FunctionType:
- return value
- return BoundMethod(value, self)
-
-class BoundMethod:
- def __init__(self, function, instance):
- self.function = function
- self.instance = instance
- def __call__(self, *args):
- print "calling", self.function, "for", self.instance, "with", args
- return apply(self.function, (self.instance,) + args)
-
-Trace = Tracing('Trace', (), {})
-
-class MyTracedClass(Trace):
- def method1(self, a):
- self.a = a
- def method2(self):
- return self.a
-
-aninstance = MyTracedClass()
-
-aninstance.method1(10)
-
-print aninstance.method2()
diff --git a/Demo/metaclasses/Synch.py b/Demo/metaclasses/Synch.py
deleted file mode 100644
index df70337924..0000000000
--- a/Demo/metaclasses/Synch.py
+++ /dev/null
@@ -1,256 +0,0 @@
-"""Synchronization metaclass.
-
-This metaclass makes it possible to declare synchronized methods.
-
-"""
-
-import thread
-
-# First we need to define a reentrant lock.
-# This is generally useful and should probably be in a standard Python
-# library module. For now, we in-line it.
-
-class Lock:
-
- """Reentrant lock.
-
- This is a mutex-like object which can be acquired by the same
- thread more than once. It keeps a reference count of the number
- of times it has been acquired by the same thread. Each acquire()
- call must be matched by a release() call and only the last
- release() call actually releases the lock for acquisition by
- another thread.
-
- The implementation uses two locks internally:
-
- __mutex is a short term lock used to protect the instance variables
- __wait is the lock for which other threads wait
-
- A thread intending to acquire both locks should acquire __wait
- first.
-
- The implementation uses two other instance variables, protected by
- locking __mutex:
-
- __tid is the thread ID of the thread that currently has the lock
- __count is the number of times the current thread has acquired it
-
- When the lock is released, __tid is None and __count is zero.
-
- """
-
- def __init__(self):
- """Constructor. Initialize all instance variables."""
- self.__mutex = thread.allocate_lock()
- self.__wait = thread.allocate_lock()
- self.__tid = None
- self.__count = 0
-
- def acquire(self, flag=1):
- """Acquire the lock.
-
- If the optional flag argument is false, returns immediately
- when it cannot acquire the __wait lock without blocking (it
- may still block for a little while in order to acquire the
- __mutex lock).
-
- The return value is only relevant when the flag argument is
- false; it is 1 if the lock is acquired, 0 if not.
-
- """
- self.__mutex.acquire()
- try:
- if self.__tid == thread.get_ident():
- self.__count = self.__count + 1
- return 1
- finally:
- self.__mutex.release()
- locked = self.__wait.acquire(flag)
- if not flag and not locked:
- return 0
- try:
- self.__mutex.acquire()
- assert self.__tid == None
- assert self.__count == 0
- self.__tid = thread.get_ident()
- self.__count = 1
- return 1
- finally:
- self.__mutex.release()
-
- def release(self):
- """Release the lock.
-
- If this thread doesn't currently have the lock, an assertion
- error is raised.
-
- Only allow another thread to acquire the lock when the count
- reaches zero after decrementing it.
-
- """
- self.__mutex.acquire()
- try:
- assert self.__tid == thread.get_ident()
- assert self.__count > 0
- self.__count = self.__count - 1
- if self.__count == 0:
- self.__tid = None
- self.__wait.release()
- finally:
- self.__mutex.release()
-
-
-def _testLock():
-
- done = []
-
- def f2(lock, done=done):
- lock.acquire()
- print "f2 running in thread %d\n" % thread.get_ident(),
- lock.release()
- done.append(1)
-
- def f1(lock, f2=f2, done=done):
- lock.acquire()
- print "f1 running in thread %d\n" % thread.get_ident(),
- try:
- f2(lock)
- finally:
- lock.release()
- done.append(1)
-
- lock = Lock()
- lock.acquire()
- f1(lock) # Adds 2 to done
- lock.release()
-
- lock.acquire()
-
- thread.start_new_thread(f1, (lock,)) # Adds 2
- thread.start_new_thread(f1, (lock, f1)) # Adds 3
- thread.start_new_thread(f2, (lock,)) # Adds 1
- thread.start_new_thread(f2, (lock,)) # Adds 1
-
- lock.release()
- import time
- while len(done) < 9:
- print len(done)
- time.sleep(0.001)
- print len(done)
-
-
-# Now, the Locking metaclass is a piece of cake.
-# As an example feature, methods whose name begins with exactly one
-# underscore are not synchronized.
-
-from Meta import MetaClass, MetaHelper, MetaMethodWrapper
-
-class LockingMethodWrapper(MetaMethodWrapper):
- def __call__(self, *args, **kw):
- if self.__name__[:1] == '_' and self.__name__[1:] != '_':
- return apply(self.func, (self.inst,) + args, kw)
- self.inst.__lock__.acquire()
- try:
- return apply(self.func, (self.inst,) + args, kw)
- finally:
- self.inst.__lock__.release()
-
-class LockingHelper(MetaHelper):
- __methodwrapper__ = LockingMethodWrapper
- def __helperinit__(self, formalclass):
- MetaHelper.__helperinit__(self, formalclass)
- self.__lock__ = Lock()
-
-class LockingMetaClass(MetaClass):
- __helper__ = LockingHelper
-
-Locking = LockingMetaClass('Locking', (), {})
-
-def _test():
- # For kicks, take away the Locking base class and see it die
- class Buffer(Locking):
- def __init__(self, initialsize):
- assert initialsize > 0
- self.size = initialsize
- self.buffer = [None]*self.size
- self.first = self.last = 0
- def put(self, item):
- # Do we need to grow the buffer?
- if (self.last+1) % self.size != self.first:
- # Insert the new item
- self.buffer[self.last] = item
- self.last = (self.last+1) % self.size
- return
- # Double the buffer size
- # First normalize it so that first==0 and last==size-1
- print "buffer =", self.buffer
- print "first = %d, last = %d, size = %d" % (
- self.first, self.last, self.size)
- if self.first <= self.last:
- temp = self.buffer[self.first:self.last]
- else:
- temp = self.buffer[self.first:] + self.buffer[:self.last]
- print "temp =", temp
- self.buffer = temp + [None]*(self.size+1)
- self.first = 0
- self.last = self.size-1
- self.size = self.size*2
- print "Buffer size doubled to", self.size
- print "new buffer =", self.buffer
- print "first = %d, last = %d, size = %d" % (
- self.first, self.last, self.size)
- self.put(item) # Recursive call to test the locking
- def get(self):
- # Is the buffer empty?
- if self.first == self.last:
- raise EOFError # Avoid defining a new exception
- item = self.buffer[self.first]
- self.first = (self.first+1) % self.size
- return item
-
- def producer(buffer, wait, n=1000):
- import time
- i = 0
- while i < n:
- print "put", i
- buffer.put(i)
- i = i+1
- print "Producer: done producing", n, "items"
- wait.release()
-
- def consumer(buffer, wait, n=1000):
- import time
- i = 0
- tout = 0.001
- while i < n:
- try:
- x = buffer.get()
- if x != i:
- raise AssertionError, \
- "get() returned %s, expected %s" % (x, i)
- print "got", i
- i = i+1
- tout = 0.001
- except EOFError:
- time.sleep(tout)
- tout = tout*2
- print "Consumer: done consuming", n, "items"
- wait.release()
-
- pwait = thread.allocate_lock()
- pwait.acquire()
- cwait = thread.allocate_lock()
- cwait.acquire()
- buffer = Buffer(1)
- n = 1000
- thread.start_new_thread(consumer, (buffer, cwait, n))
- thread.start_new_thread(producer, (buffer, pwait, n))
- pwait.acquire()
- print "Producer done"
- cwait.acquire()
- print "All done"
- print "buffer size ==", len(buffer.buffer)
-
-if __name__ == '__main__':
- _testLock()
- _test()
diff --git a/Demo/metaclasses/Trace.py b/Demo/metaclasses/Trace.py
deleted file mode 100644
index 86e199d602..0000000000
--- a/Demo/metaclasses/Trace.py
+++ /dev/null
@@ -1,145 +0,0 @@
-"""Tracing metaclass.
-
-XXX This is very much a work in progress.
-
-"""
-
-import types, sys
-
-class TraceMetaClass:
- """Metaclass for tracing.
-
- Classes defined using this metaclass have an automatic tracing
- feature -- by setting the __trace_output__ instance (or class)
- variable to a file object, trace messages about all calls are
- written to the file. The trace formatting can be changed by
- defining a suitable __trace_call__ method.
-
- """
-
- __inited = 0
-
- def __init__(self, name, bases, dict):
- self.__name__ = name
- self.__bases__ = bases
- self.__dict = dict
- # XXX Can't define __dict__, alas
- self.__inited = 1
-
- def __getattr__(self, name):
- try:
- return self.__dict[name]
- except KeyError:
- for base in self.__bases__:
- try:
- return base.__getattr__(name)
- except AttributeError:
- pass
- raise AttributeError, name
-
- def __setattr__(self, name, value):
- if not self.__inited:
- self.__dict__[name] = value
- else:
- self.__dict[name] = value
-
- def __call__(self, *args, **kw):
- inst = TracingInstance()
- inst.__meta_init__(self)
- try:
- init = inst.__getattr__('__init__')
- except AttributeError:
- init = lambda: None
- apply(init, args, kw)
- return inst
-
- __trace_output__ = None
-
-class TracingInstance:
- """Helper class to represent an instance of a tracing class."""
-
- def __trace_call__(self, fp, fmt, *args):
- fp.write((fmt+'\n') % args)
-
- def __meta_init__(self, klass):
- self.__class = klass
-
- def __getattr__(self, name):
- # Invoked for any attr not in the instance's __dict__
- try:
- raw = self.__class.__getattr__(name)
- except AttributeError:
- raise AttributeError, name
- if type(raw) != types.FunctionType:
- return raw
- # It's a function
- fullname = self.__class.__name__ + "." + name
- if not self.__trace_output__ or name == '__trace_call__':
- return NotTracingWrapper(fullname, raw, self)
- else:
- return TracingWrapper(fullname, raw, self)
-
-class NotTracingWrapper:
- def __init__(self, name, func, inst):
- self.__name__ = name
- self.func = func
- self.inst = inst
- def __call__(self, *args, **kw):
- return apply(self.func, (self.inst,) + args, kw)
-
-class TracingWrapper(NotTracingWrapper):
- def __call__(self, *args, **kw):
- self.inst.__trace_call__(self.inst.__trace_output__,
- "calling %s, inst=%s, args=%s, kw=%s",
- self.__name__, self.inst, args, kw)
- try:
- rv = apply(self.func, (self.inst,) + args, kw)
- except:
- t, v, tb = sys.exc_info()
- self.inst.__trace_call__(self.inst.__trace_output__,
- "returning from %s with exception %s: %s",
- self.__name__, t, v)
- raise t, v, tb
- else:
- self.inst.__trace_call__(self.inst.__trace_output__,
- "returning from %s with value %s",
- self.__name__, rv)
- return rv
-
-Traced = TraceMetaClass('Traced', (), {'__trace_output__': None})
-
-
-def _test():
- global C, D
- class C(Traced):
- def __init__(self, x=0): self.x = x
- def m1(self, x): self.x = x
- def m2(self, y): return self.x + y
- __trace_output__ = sys.stdout
- class D(C):
- def m2(self, y): print "D.m2(%s)" % `y`; return C.m2(self, y)
- __trace_output__ = None
- x = C(4321)
- print x
- print x.x
- print x.m1(100)
- print x.m1(10)
- print x.m2(33)
- print x.m1(5)
- print x.m2(4000)
- print x.x
-
- print C.__init__
- print C.m2
- print D.__init__
- print D.m2
-
- y = D()
- print y
- print y.m1(10)
- print y.m2(100)
- print y.x
-
-if __name__ == '__main__':
- _test()
-
diff --git a/Demo/metaclasses/index.html b/Demo/metaclasses/index.html
deleted file mode 100644
index af9caa9f58..0000000000
--- a/Demo/metaclasses/index.html
+++ /dev/null
@@ -1,605 +0,0 @@
-
-
-
-Metaclasses in Python 1.5
-
-
-
-
-
Metaclasses in Python 1.5
-
(A.k.a. The Killer Joke :-)
-
-
-
-(Postscript: reading this essay is probably not the best way to
-understand the metaclass hook described here. See a message posted by Vladimir Marangozov
-which may give a gentler introduction to the matter. You may also
-want to search Deja News for messages with "metaclass" in the subject
-posted to comp.lang.python in July and August 1998.)
-
-
-
-
In previous Python releases (and still in 1.5), there is something
-called the ``Don Beaudry hook'', after its inventor and champion.
-This allows C extensions to provide alternate class behavior, thereby
-allowing the Python class syntax to be used to define other class-like
-entities. Don Beaudry has used this in his infamous MESS package; Jim
-Fulton has used it in his Extension
-Classes package. (It has also been referred to as the ``Don
-Beaudry hack,'' but that's a misnomer. There's nothing hackish
-about it -- in fact, it is rather elegant and deep, even though
-there's something dark to it.)
-
-
(On first reading, you may want to skip directly to the examples in
-the section "Writing Metaclasses in Python" below, unless you want
-your head to explode.)
-
-
-
-
-
-
Documentation of the Don Beaudry hook has purposefully been kept
-minimal, since it is a feature of incredible power, and is easily
-abused. Basically, it checks whether the type of the base
-class is callable, and if so, it is called to create the new
-class.
-
-
Note the two indirection levels. Take a simple example:
-
-
-class B:
- pass
-
-class C(B):
- pass
-
-
-Take a look at the second class definition, and try to fathom ``the
-type of the base class is callable.''
-
-
(Types are not classes, by the way. See questions 4.2, 4.19 and in
-particular 6.22 in the Python FAQ
-for more on this topic.)
-
-
-
-
-
-
The base class is B; this one's easy.
-
-
Since B is a class, its type is ``class''; so the type of the
-base class is the type ``class''. This is also known as
-types.ClassType, assuming the standard module types has
-been imported.
-
-
Now is the type ``class'' callable? No, because types (in
-core Python) are never callable. Classes are callable (calling a
-class creates a new instance) but types aren't.
-
-
-
-
So our conclusion is that in our example, the type of the base
-class (of C) is not callable. So the Don Beaudry hook does not apply,
-and the default class creation mechanism is used (which is also used
-when there is no base class). In fact, the Don Beaudry hook never
-applies when using only core Python, since the type of a core object
-is never callable.
-
-
So what do Don and Jim do in order to use Don's hook? Write an
-extension that defines at least two new Python object types. The
-first would be the type for ``class-like'' objects usable as a base
-class, to trigger Don's hook. This type must be made callable.
-That's why we need a second type. Whether an object is callable
-depends on its type. So whether a type object is callable depends on
-its type, which is a meta-type. (In core Python there
-is only one meta-type, the type ``type'' (types.TypeType), which is
-the type of all type objects, even itself.) A new meta-type must
-be defined that makes the type of the class-like objects callable.
-(Normally, a third type would also be needed, the new ``instance''
-type, but this is not an absolute requirement -- the new class type
-could return an object of some existing type when invoked to create an
-instance.)
-
-
Still confused? Here's a simple device due to Don himself to
-explain metaclasses. Take a simple class definition; assume B is a
-special class that triggers Don's hook:
-
-
-class C(B):
- a = 1
- b = 2
-
-
-This can be though of as equivalent to:
-
-
-C = type(B)('C', (B,), {'a': 1, 'b': 2})
-
-
-If that's too dense for you, here's the same thing written out using
-temporary variables:
-
-
-creator = type(B) # The type of the base class
-name = 'C' # The name of the new class
-bases = (B,) # A tuple containing the base class(es)
-namespace = {'a': 1, 'b': 2} # The namespace of the class statement
-C = creator(name, bases, namespace)
-
-
-This is analogous to what happens without the Don Beaudry hook, except
-that in that case the creator function is set to the default class
-creator.
-
-
In either case, the creator is called with three arguments. The
-first one, name, is the name of the new class (as given at the
-top of the class statement). The bases argument is a tuple of
-base classes (a singleton tuple if there's only one base class, like
-the example). Finally, namespace is a dictionary containing
-the local variables collected during execution of the class statement.
-
-
Note that the contents of the namespace dictionary is simply
-whatever names were defined in the class statement. A little-known
-fact is that when Python executes a class statement, it enters a new
-local namespace, and all assignments and function definitions take
-place in this namespace. Thus, after executing the following class
-statement:
-
-
-class C:
- a = 1
- def f(s): pass
-
-
-the class namespace's contents would be {'a': 1, 'f': <function f
-...>}.
-
-
But enough already about writing Python metaclasses in C; read the
-documentation of MESS or Extension
-Classes for more information.
-
-
-
-
-
-
Writing Metaclasses in Python
-
-
In Python 1.5, the requirement to write a C extension in order to
-write metaclasses has been dropped (though you can still do
-it, of course). In addition to the check ``is the type of the base
-class callable,'' there's a check ``does the base class have a
-__class__ attribute.'' If so, it is assumed that the __class__
-attribute refers to a class.
-
-
Let's repeat our simple example from above:
-
-
-class C(B):
- a = 1
- b = 2
-
-
-Assuming B has a __class__ attribute, this translates into:
-
-
-C = B.__class__('C', (B,), {'a': 1, 'b': 2})
-
-
-This is exactly the same as before except that instead of type(B),
-B.__class__ is invoked. If you have read FAQ question 6.22 you will understand that while there is a big
-technical difference between type(B) and B.__class__, they play the
-same role at different abstraction levels. And perhaps at some point
-in the future they will really be the same thing (at which point you
-would be able to derive subclasses from built-in types).
-
-
At this point it may be worth mentioning that C.__class__ is the
-same object as B.__class__, i.e., C's metaclass is the same as B's
-metaclass. In other words, subclassing an existing class creates a
-new (meta)inststance of the base class's metaclass.
-
-
Going back to the example, the class B.__class__ is instantiated,
-passing its constructor the same three arguments that are passed to
-the default class constructor or to an extension's metaclass:
-name, bases, and namespace.
-
-
It is easy to be confused by what exactly happens when using a
-metaclass, because we lose the absolute distinction between classes
-and instances: a class is an instance of a metaclass (a
-``metainstance''), but technically (i.e. in the eyes of the python
-runtime system), the metaclass is just a class, and the metainstance
-is just an instance. At the end of the class statement, the metaclass
-whose metainstance is used as a base class is instantiated, yielding a
-second metainstance (of the same metaclass). This metainstance is
-then used as a (normal, non-meta) class; instantiation of the class
-means calling the metainstance, and this will return a real instance.
-And what class is that an instance of? Conceptually, it is of course
-an instance of our metainstance; but in most cases the Python runtime
-system will see it as an instance of a a helper class used by the
-metaclass to implement its (non-meta) instances...
-
-
Hopefully an example will make things clearer. Let's presume we
-have a metaclass MetaClass1. It's helper class (for non-meta
-instances) is callled HelperClass1. We now (manually) instantiate
-MetaClass1 once to get an empty special base class:
-
-
-BaseClass1 = MetaClass1("BaseClass1", (), {})
-
-
-We can now use BaseClass1 as a base class in a class statement:
-
-
-
-At this point, MySpecialClass is defined; it is a metainstance of
-MetaClass1 just like BaseClass1, and in fact the expression
-``BaseClass1.__class__ == MySpecialClass.__class__ == MetaClass1''
-yields true.
-
-
We are now ready to create instances of MySpecialClass. Let's
-assume that no constructor arguments are required:
-
-
-
-The print statement shows that x and y are instances of HelperClass1.
-How did this happen? MySpecialClass is an instance of MetaClass1
-(``meta'' is irrelevant here); when an instance is called, its
-__call__ method is invoked, and presumably the __call__ method defined
-by MetaClass1 returns an instance of HelperClass1.
-
-
Now let's see how we could use metaclasses -- what can we do
-with metaclasses that we can't easily do without them? Here's one
-idea: a metaclass could automatically insert trace calls for all
-method calls. Let's first develop a simplified example, without
-support for inheritance or other ``advanced'' Python features (we'll
-add those later).
-
-
-import types
-
-class Tracing:
- def __init__(self, name, bases, namespace):
- """Create a new class."""
- self.__name__ = name
- self.__bases__ = bases
- self.__namespace__ = namespace
- def __call__(self):
- """Create a new instance."""
- return Instance(self)
-
-class Instance:
- def __init__(self, klass):
- self.__klass__ = klass
- def __getattr__(self, name):
- try:
- value = self.__klass__.__namespace__[name]
- except KeyError:
- raise AttributeError, name
- if type(value) is not types.FunctionType:
- return value
- return BoundMethod(value, self)
-
-class BoundMethod:
- def __init__(self, function, instance):
- self.function = function
- self.instance = instance
- def __call__(self, *args):
- print "calling", self.function, "for", self.instance, "with", args
- return apply(self.function, (self.instance,) + args)
-
-Trace = Tracing('Trace', (), {})
-
-class MyTracedClass(Trace):
- def method1(self, a):
- self.a = a
- def method2(self):
- return self.a
-
-aninstance = MyTracedClass()
-
-aninstance.method1(10)
-
-print "the answer is %d" % aninstance.method2()
-
-
-Confused already? The intention is to read this from top down. The
-Tracing class is the metaclass we're defining. Its structure is
-really simple.
-
-
-
-
-
-
The __init__ method is invoked when a new Tracing instance is
-created, e.g. the definition of class MyTracedClass later in the
-example. It simply saves the class name, base classes and namespace
-as instance variables.
-
-
The __call__ method is invoked when a Tracing instance is called,
-e.g. the creation of aninstance later in the example. It returns an
-instance of the class Instance, which is defined next.
-
-
-
-
The class Instance is the class used for all instances of classes
-built using the Tracing metaclass, e.g. aninstance. It has two
-methods:
-
-
-
-
-
-
The __init__ method is invoked from the Tracing.__call__ method
-above to initialize a new instance. It saves the class reference as
-an instance variable. It uses a funny name because the user's
-instance variables (e.g. self.a later in the example) live in the same
-namespace.
-
-
The __getattr__ method is invoked whenever the user code
-references an attribute of the instance that is not an instance
-variable (nor a class variable; but except for __init__ and
-__getattr__ there are no class variables). It will be called, for
-example, when aninstance.method1 is referenced in the example, with
-self set to aninstance and name set to the string "method1".
-
-
-
-
The __getattr__ method looks the name up in the __namespace__
-dictionary. If it isn't found, it raises an AttributeError exception.
-(In a more realistic example, it would first have to look through the
-base classes as well.) If it is found, there are two possibilities:
-it's either a function or it isn't. If it's not a function, it is
-assumed to be a class variable, and its value is returned. If it's a
-function, we have to ``wrap'' it in instance of yet another helper
-class, BoundMethod.
-
-
The BoundMethod class is needed to implement a familiar feature:
-when a method is defined, it has an initial argument, self, which is
-automatically bound to the relevant instance when it is called. For
-example, aninstance.method1(10) is equivalent to method1(aninstance,
-10). In the example if this call, first a temporary BoundMethod
-instance is created with the following constructor call: temp =
-BoundMethod(method1, aninstance); then this instance is called as
-temp(10). After the call, the temporary instance is discarded.
-
-
-
-
-
-
The __init__ method is invoked for the constructor call
-BoundMethod(method1, aninstance). It simply saves away its
-arguments.
-
-
The __call__ method is invoked when the bound method instance is
-called, as in temp(10). It needs to call method1(aninstance, 10).
-However, even though self.function is now method1 and self.instance is
-aninstance, it can't call self.function(self.instance, args) directly,
-because it should work regardless of the number of arguments passed.
-(For simplicity, support for keyword arguments has been omitted.)
-
-
-
-
In order to be able to support arbitrary argument lists, the
-__call__ method first constructs a new argument tuple. Conveniently,
-because of the notation *args in __call__'s own argument list, the
-arguments to __call__ (except for self) are placed in the tuple args.
-To construct the desired argument list, we concatenate a singleton
-tuple containing the instance with the args tuple: (self.instance,) +
-args. (Note the trailing comma used to construct the singleton
-tuple.) In our example, the resulting argument tuple is (aninstance,
-10).
-
-
The intrinsic function apply() takes a function and an argument
-tuple and calls the function for it. In our example, we are calling
-apply(method1, (aninstance, 10)) which is equivalent to calling
-method(aninstance, 10).
-
-
From here on, things should come together quite easily. The output
-of the example code is something like this:
-
-
-calling <function method1 at ae8d8> for <Instance instance at 95ab0> with (10,)
-calling <function method2 at ae900> for <Instance instance at 95ab0> with ()
-the answer is 10
-
-
-
That was about the shortest meaningful example that I could come up
-with. A real tracing metaclass (for example, Trace.py discussed below) needs to be more
-complicated in two dimensions.
-
-
First, it needs to support more advanced Python features such as
-class variables, inheritance, __init__ methods, and keyword arguments.
-
-
Second, it needs to provide a more flexible way to handle the
-actual tracing information; perhaps it should be possible to write
-your own tracing function that gets called, perhaps it should be
-possible to enable and disable tracing on a per-class or per-instance
-basis, and perhaps a filter so that only interesting calls are traced;
-it should also be able to trace the return value of the call (or the
-exception it raised if an error occurs). Even the Trace.py example
-doesn't support all these features yet.
-
-
-
-
-
-
Real-life Examples
-
-
Have a look at some very preliminary examples that I coded up to
-teach myself how to write metaclasses:
-
-
This (ab)uses the class syntax as an elegant way to define
-enumerated types. The resulting classes are never instantiated --
-rather, their class attributes are the enumerated values. For
-example:
-
-
-class Color(Enum):
- red = 1
- green = 2
- blue = 3
-print Color.red
-
-
-will print the string ``Color.red'', while ``Color.red==1'' is true,
-and ``Color.red + 1'' raise a TypeError exception.
-
-
The resulting classes work much like standard
-classes, but by setting a special class or instance attribute
-__trace_output__ to point to a file, all calls to the class's methods
-are traced. It was a bit of a struggle to get this right. This
-should probably redone using the generic metaclass below.
-
-
A generic metaclass. This is an attempt at finding out how much
-standard class behavior can be mimicked by a metaclass. The
-preliminary answer appears to be that everything's fine as long as the
-class (or its clients) don't look at the instance's __class__
-attribute, nor at the class's __dict__ attribute. The use of
-__getattr__ internally makes the classic implementation of __getattr__
-hooks tough; we provide a similar hook _getattr_ instead.
-(__setattr__ and __delattr__ are not affected.)
-(XXX Hm. Could detect presence of __getattr__ and rename it.)
-
-
A pattern seems to be emerging: almost all these uses of
-metaclasses (except for Enum, which is probably more cute than useful)
-mostly work by placing wrappers around method calls. An obvious
-problem with that is that it's not easy to combine the features of
-different metaclasses, while this would actually be quite useful: for
-example, I wouldn't mind getting a trace from the test run of the
-Synch module, and it would be interesting to add preconditions to it
-as well. This needs more research. Perhaps a metaclass could be
-provided that allows stackable wrappers...
-
-
-
-
-
-
Things You Could Do With Metaclasses
-
-
There are lots of things you could do with metaclasses. Most of
-these can also be done with creative use of __getattr__, but
-metaclasses make it easier to modify the attribute lookup behavior of
-classes. Here's a partial list.
-
-
-
-
-
-
Enforce different inheritance semantics, e.g. automatically call
-base class methods when a derived class overrides
-
-
Implement class methods (e.g. if the first argument is not named
-'self')
-
-
Implement that each instance is initialized with copies of
-all class variables
-
-
Implement a different way to store instance variables (e.g. in a
-list kept outside the the instance but indexed by the instance's id())
-
-
Automatically wrap or trap all or certain methods
-
-
-
-
for tracing
-
-
for precondition and postcondition checking
-
-
for synchronized methods
-
-
for automatic value caching
-
-
-
-
-
When an attribute is a parameterless function, call it on
-reference (to mimic it being an instance variable); same on assignment
-
-
Instrumentation: see how many times various attributes are used
-
-
Different semantics for __setattr__ and __getattr__ (e.g. disable
-them when they are being used recursively)
-
-
Abuse class syntax for other things
-
-
Experiment with automatic type checking
-
-
Delegation (or acquisition)
-
-
Dynamic inheritance patterns
-
-
Automatic caching of methods
-
-
-
-
-
-
-
-
Credits
-
-
Many thanks to David Ascher and Donald Beaudry for their comments
-on earlier draft of this paper. Also thanks to Matt Conway and Tommy
-Burnette for putting a seed for the idea of metaclasses in my
-mind, nearly three years ago, even though at the time my response was
-``you can do that with __getattr__ hooks...'' :-)
-
-
-
-
-
-
-
-
diff --git a/Demo/metaclasses/meta-vladimir.txt b/Demo/metaclasses/meta-vladimir.txt
deleted file mode 100644
index 36406bb465..0000000000
--- a/Demo/metaclasses/meta-vladimir.txt
+++ /dev/null
@@ -1,256 +0,0 @@
-Subject: Re: The metaclass saga using Python
-From: Vladimir Marangozov
-To: tim_one@email.msn.com (Tim Peters)
-Cc: python-list@cwi.nl
-Date: Wed, 5 Aug 1998 15:59:06 +0200 (DFT)
-
-[Tim]
->
-> building-on-examples-tends-to-prevent-abstract-thrashing-ly y'rs - tim
->
-
-OK, I stand corrected. I understand that anybody's interpretation of
-the meta-class concept is likely to be difficult to digest by others.
-
-Here's another try, expressing the same thing, but using the Python
-programming model, examples and, perhaps, more popular terms.
-
-1. Classes.
-
- This is pure Python of today. Sorry about the tutorial, but it is
- meant to illustrate the second part, which is the one we're
- interested in and which will follow the same development scenario.
- Besides, newbies are likely to understand that the discussion is
- affordable even for them :-)
-
- a) Class definition
-
- A class is meant to define the common properties of a set of objects.
- A class is a "package" of properties. The assembly of properties
- in a class package is sometimes called a class structure (which isn't
- always appropriate).
-
- >>> class A:
- attr1 = "Hello" # an attribute of A
- def method1(self, *args): pass # method1 of A
- def method2(self, *args): pass # method2 of A
- >>>
-
- So far, we defined the structure of the class A. The class A is
- of type . We can check this by asking Python: "what is A?"
-
- >>> A # What is A?
-
-
- b) Class instantiation
-
- Creating an object with the properties defined in the class A is
- called instantiation of the class A. After an instantiation of A, we
- obtain a new object, called an instance, which has the properties
- packaged in the class A.
-
- >>> a = A() # 'a' is the 1st instance of A
- >>> a # What is 'a'?
- <__main__.A instance at 2022b9d0>
-
- >>> b = A() # 'b' is another instance of A
- >>> b # What is 'b'?
- <__main__.A instance at 2022b9c0>
-
- The objects, 'a' and 'b', are of type and they both have
- the same properties. Note, that 'a' and 'b' are different objects.
- (their adresses differ). This is a bit hard to see, so let's ask Python:
-
- >>> a == b # Is 'a' the same object as 'b'?
- 0 # No.
-
- Instance objects have one more special property, indicating the class
- they are an instance of. This property is named __class__.
-
- >>> a.__class__ # What is the class of 'a'?
- # 'a' is an instance of A
- >>> b.__class__ # What is the class of 'b'?
- # 'b' is an instance of A
- >>> a.__class__ == b.__class__ # Is it really the same class A?
- 1 # Yes.
-
- c) Class inheritance (class composition and specialization)
-
- Classes can be defined in terms of other existing classes (and only
- classes! -- don't bug me on this now). Thus, we can compose property
- packages and create new ones. We reuse the property set defined
- in a class by defining a new class, which "inherits" from the former.
- In other words, a class B which inherits from the class A, inherits
- the properties defined in A, or, B inherits the structure of A.
-
- In the same time, at the definition of the new class B, we can enrich
- the inherited set of properties by adding new ones and/or modify some
- of the inherited properties.
-
- >>> class B(A): # B inherits A's properties
- attr2 = "World" # additional attr2
- def method2(self, arg1): pass # method2 is redefined
- def method3(self, *args): pass # additional method3
-
- >>> B # What is B?
-
- >>> B == A # Is B the same class as A?
- 0 # No.
-
- Classes define one special property, indicating whether a class
- inherits the properties of another class. This property is called
- __bases__ and it contains a list (a tuple) of the classes the new
- class inherits from. The classes from which a class is inheriting the
- properties are called superclasses (in Python, we call them also --
- base classes).
-
- >>> A.__bases__ # Does A have any superclasses?
- () # No.
- >>> B.__bases__ # Does B have any superclasses?
- (,) # Yes. It has one superclass.
- >>> B.__bases__[0] == A # Is it really the class A?
- 1 # Yes, it is.
-
---------
-
- Congratulations on getting this far! This was the hard part.
- Now, let's continue with the easy one.
-
---------
-
-2. Meta-classes
-
- You have to admit, that an anonymous group of Python wizards are
- not satisfied with the property packaging facilities presented above.
- They say, that the Real-World bugs them with problems that cannot be
- modelled successfully with classes. Or, that the way classes are
- implemented in Python and the way classes and instances behave at
- runtime isn't always appropriate for reproducing the Real-World's
- behavior in a way that satisfies them.
-
- Hence, what they want is the following:
-
- a) leave objects as they are (instances of classes)
- b) leave classes as they are (property packages and object creators)
-
- BUT, at the same time:
-
- c) consider classes as being instances of mysterious objects.
- d) label mysterious objects "meta-classes".
-
- Easy, eh?
-
- You may ask: "Why on earth do they want to do that?".
- They answer: "Poor soul... Go and see how cruel the Real-World is!".
- You - fuzzy: "OK, will do!"
-
- And here we go for another round of what I said in section 1 -- Classes.
-
- However, be warned! The features we're going to talk about aren't fully
- implemented yet, because the Real-World don't let wizards to evaluate
- precisely how cruel it is, so the features are still highly-experimental.
-
- a) Meta-class definition
-
- A meta-class is meant to define the common properties of a set of
- classes. A meta-class is a "package" of properties. The assembly
- of properties in a meta-class package is sometimes called a meta-class
- structure (which isn't always appropriate).
-
- In Python, a meta-class definition would have looked like this:
-
- >>> metaclass M:
- attr1 = "Hello" # an attribute of M
- def method1(self, *args): pass # method1 of M
- def method2(self, *args): pass # method2 of M
- >>>
-
- So far, we defined the structure of the meta-class M. The meta-class
- M is of type . We cannot check this by asking Python, but
- if we could, it would have answered:
-
- >>> M # What is M?
-
-
- b) Meta-class instantiation
-
- Creating an object with the properties defined in the meta-class M is
- called instantiation of the meta-class M. After an instantiation of M,
- we obtain a new object, called an class, but now it is called also
- a meta-instance, which has the properties packaged in the meta-class M.
-
- In Python, instantiating a meta-class would have looked like this:
-
- >>> A = M() # 'A' is the 1st instance of M
- >>> A # What is 'A'?
-
-
- >>> B = M() # 'B' is another instance of M
- >>> B # What is 'B'?
-
-
- The metaclass-instances, A and B, are of type and they both
- have the same properties. Note, that A and B are different objects.
- (their adresses differ). This is a bit hard to see, but if it was
- possible to ask Python, it would have answered:
-
- >>> A == B # Is A the same class as B?
- 0 # No.
-
- Class objects have one more special property, indicating the meta-class
- they are an instance of. This property is named __metaclass__.
-
- >>> A.__metaclass__ # What is the meta-class of A?
- # A is an instance of M
- >>> A.__metaclass__ # What is the meta-class of B?
- # B is an instance of M
- >>> A.__metaclass__ == B.__metaclass__ # Is it the same meta-class M?
- 1 # Yes.
-
- c) Meta-class inheritance (meta-class composition and specialization)
-
- Meta-classes can be defined in terms of other existing meta-classes
- (and only meta-classes!). Thus, we can compose property packages and
- create new ones. We reuse the property set defined in a meta-class by
- defining a new meta-class, which "inherits" from the former.
- In other words, a meta-class N which inherits from the meta-class M,
- inherits the properties defined in M, or, N inherits the structure of M.
-
- In the same time, at the definition of the new meta-class N, we can
- enrich the inherited set of properties by adding new ones and/or modify
- some of the inherited properties.
-
- >>> metaclass N(M): # N inherits M's properties
- attr2 = "World" # additional attr2
- def method2(self, arg1): pass # method2 is redefined
- def method3(self, *args): pass # additional method3
-
- >>> N # What is N?
-
- >>> N == M # Is N the same meta-class as M?
- 0 # No.
-
- Meta-classes define one special property, indicating whether a
- meta-class inherits the properties of another meta-class. This property
- is called __metabases__ and it contains a list (a tuple) of the
- meta-classes the new meta-class inherits from. The meta-classes from
- which a meta-class is inheriting the properties are called
- super-meta-classes (in Python, we call them also -- super meta-bases).
-
- >>> M.__metabases__ # Does M have any supermetaclasses?
- () # No.
- >>> N.__metabases__ # Does N have any supermetaclasses?
- (,) # Yes. It has a supermetaclass.
- >>> N.__metabases__[0] == M # Is it really the meta-class M?
- 1 # Yes, it is.
-
---------
-
- Triple congratulations on getting this far!
- Now you know everything about meta-classes and the Real-World!
-
-
-
---
- Vladimir MARANGOZOV | Vladimir.Marangozov@inrialpes.fr
-http://sirac.inrialpes.fr/~marangoz | tel:(+33-4)76615277 fax:76615252
diff --git a/Demo/newmetaclasses/Eiffel.py b/Demo/newmetaclasses/Eiffel.py
deleted file mode 100644
index 1dd7e6c17f..0000000000
--- a/Demo/newmetaclasses/Eiffel.py
+++ /dev/null
@@ -1,144 +0,0 @@
-"""Support Eiffel-style preconditions and postconditions."""
-
-from new import function
-
-class EiffelBaseMetaClass(type):
-
- def __new__(meta, name, bases, dict):
- meta.convert_methods(dict)
- return super(EiffelBaseMetaClass, meta).__new__(meta, name, bases,
- dict)
-
- def convert_methods(cls, dict):
- """Replace functions in dict with EiffelMethod wrappers.
-
- The dict is modified in place.
-
- If a method ends in _pre or _post, it is removed from the dict
- regardless of whether there is a corresponding method.
- """
- # find methods with pre or post conditions
- methods = []
- for k, v in dict.iteritems():
- if k.endswith('_pre') or k.endswith('_post'):
- assert isinstance(v, function)
- elif isinstance(v, function):
- methods.append(k)
- for m in methods:
- pre = dict.get("%s_pre" % m)
- post = dict.get("%s_post" % m)
- if pre or post:
- dict[k] = cls.make_eiffel_method(dict[m], pre, post)
-
- convert_methods = classmethod(convert_methods)
-
-class EiffelMetaClass1(EiffelBaseMetaClass):
- # an implementation of the "eiffel" meta class that uses nested functions
-
- def make_eiffel_method(func, pre, post):
- def method(self, *args, **kwargs):
- if pre:
- pre(self, *args, **kwargs)
- x = func(self, *args, **kwargs)
- if post:
- post(self, x, *args, **kwargs)
- return x
-
- if func.__doc__:
- method.__doc__ = func.__doc__
-
- return method
-
- make_eiffel_method = staticmethod(make_eiffel_method)
-
-class EiffelMethodWrapper:
-
- def __init__(self, inst, descr):
- self._inst = inst
- self._descr = descr
-
- def __call__(self, *args, **kwargs):
- return self._descr.callmethod(self._inst, args, kwargs)
-
-class EiffelDescriptor(object):
-
- def __init__(self, func, pre, post):
- self._func = func
- self._pre = pre
- self._post = post
-
- self.__name__ = func.__name__
- self.__doc__ = func.__doc__
-
- def __get__(self, obj, cls):
- return EiffelMethodWrapper(obj, self)
-
- def callmethod(self, inst, args, kwargs):
- if self._pre:
- self._pre(inst, *args, **kwargs)
- x = self._func(inst, *args, **kwargs)
- if self._post:
- self._post(inst, x, *args, **kwargs)
- return x
-
-class EiffelMetaClass2(EiffelBaseMetaClass):
- # an implementation of the "eiffel" meta class that uses descriptors
-
- make_eiffel_method = EiffelDescriptor
-
-def _test(metaclass):
- class Eiffel:
- __metaclass__ = metaclass
-
- class Test(Eiffel):
-
- def m(self, arg):
- """Make it a little larger"""
- return arg + 1
-
- def m2(self, arg):
- """Make it a little larger"""
- return arg + 1
-
- def m2_pre(self, arg):
- assert arg > 0
-
- def m2_post(self, result, arg):
- assert result > arg
-
- class Sub(Test):
- def m2(self, arg):
- return arg**2
- def m2_post(self, Result, arg):
- super(Sub, self).m2_post(Result, arg)
- assert Result < 100
-
- t = Test()
- t.m(1)
- t.m2(1)
- try:
- t.m2(0)
- except AssertionError:
- pass
- else:
- assert False
-
- s = Sub()
- try:
- s.m2(1)
- except AssertionError:
- pass # result == arg
- else:
- assert False
- try:
- s.m2(10)
- except AssertionError:
- pass # result == 100
- else:
- assert False
- s.m2(5)
-
-if __name__ == "__main__":
- _test(EiffelMetaClass1)
- _test(EiffelMetaClass2)
-
diff --git a/Demo/newmetaclasses/Enum.py b/Demo/newmetaclasses/Enum.py
deleted file mode 100644
index 8a00b59f21..0000000000
--- a/Demo/newmetaclasses/Enum.py
+++ /dev/null
@@ -1,178 +0,0 @@
-"""Enumeration metaclass."""
-
-class EnumMetaclass(type):
- """Metaclass for enumeration.
-
- To define your own enumeration, do something like
-
- class Color(Enum):
- red = 1
- green = 2
- blue = 3
-
- Now, Color.red, Color.green and Color.blue behave totally
- different: they are enumerated values, not integers.
-
- Enumerations cannot be instantiated; however they can be
- subclassed.
- """
-
- def __init__(cls, name, bases, dict):
- super(EnumMetaclass, cls).__init__(name, bases, dict)
- cls._members = []
- for attr in dict.keys():
- if not (attr.startswith('__') and attr.endswith('__')):
- enumval = EnumInstance(name, attr, dict[attr])
- setattr(cls, attr, enumval)
- cls._members.append(attr)
-
- def __getattr__(cls, name):
- if name == "__members__":
- return cls._members
- raise AttributeError, name
-
- def __repr__(cls):
- s1 = s2 = ""
- enumbases = [base.__name__ for base in cls.__bases__
- if isinstance(base, EnumMetaclass) and not base is Enum]
- if enumbases:
- s1 = "(%s)" % ", ".join(enumbases)
- enumvalues = ["%s: %d" % (val, getattr(cls, val))
- for val in cls._members]
- if enumvalues:
- s2 = ": {%s}" % ", ".join(enumvalues)
- return "%s%s%s" % (cls.__name__, s1, s2)
-
-class FullEnumMetaclass(EnumMetaclass):
- """Metaclass for full enumerations.
-
- A full enumeration displays all the values defined in base classes.
- """
-
- def __init__(cls, name, bases, dict):
- super(FullEnumMetaclass, cls).__init__(name, bases, dict)
- for obj in cls.__mro__:
- if isinstance(obj, EnumMetaclass):
- for attr in obj._members:
- # XXX inefficient
- if not attr in cls._members:
- cls._members.append(attr)
-
-class EnumInstance(int):
- """Class to represent an enumeration value.
-
- EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves
- like the integer 12 when compared, but doesn't support arithmetic.
-
- XXX Should it record the actual enumeration rather than just its
- name?
- """
-
- def __new__(cls, classname, enumname, value):
- return int.__new__(cls, value)
-
- def __init__(self, classname, enumname, value):
- self.__classname = classname
- self.__enumname = enumname
-
- def __repr__(self):
- return "EnumInstance(%s, %s, %d)" % (self.__classname, self.__enumname,
- self)
-
- def __str__(self):
- return "%s.%s" % (self.__classname, self.__enumname)
-
-class Enum:
- __metaclass__ = EnumMetaclass
-
-class FullEnum:
- __metaclass__ = FullEnumMetaclass
-
-def _test():
-
- class Color(Enum):
- red = 1
- green = 2
- blue = 3
-
- print Color.red
-
- print `Color.red`
- print Color.red == Color.red
- print Color.red == Color.blue
- print Color.red == 1
- print Color.red == 2
-
- class ExtendedColor(Color):
- white = 0
- orange = 4
- yellow = 5
- purple = 6
- black = 7
-
- print ExtendedColor.orange
- print ExtendedColor.red
-
- print Color.red == ExtendedColor.red
-
- class OtherColor(Enum):
- white = 4
- blue = 5
-
- class MergedColor(Color, OtherColor):
- pass
-
- print MergedColor.red
- print MergedColor.white
-
- print Color
- print ExtendedColor
- print OtherColor
- print MergedColor
-
-def _test2():
-
- class Color(FullEnum):
- red = 1
- green = 2
- blue = 3
-
- print Color.red
-
- print `Color.red`
- print Color.red == Color.red
- print Color.red == Color.blue
- print Color.red == 1
- print Color.red == 2
-
- class ExtendedColor(Color):
- white = 0
- orange = 4
- yellow = 5
- purple = 6
- black = 7
-
- print ExtendedColor.orange
- print ExtendedColor.red
-
- print Color.red == ExtendedColor.red
-
- class OtherColor(FullEnum):
- white = 4
- blue = 5
-
- class MergedColor(Color, OtherColor):
- pass
-
- print MergedColor.red
- print MergedColor.white
-
- print Color
- print ExtendedColor
- print OtherColor
- print MergedColor
-
-if __name__ == '__main__':
- _test()
- _test2()
-
diff --git a/Demo/parser/FILES b/Demo/parser/FILES
deleted file mode 100644
index 1ff59a31a2..0000000000
--- a/Demo/parser/FILES
+++ /dev/null
@@ -1,6 +0,0 @@
-Demo/parser
-Doc/libparser.tex
-Lib/AST.py
-Lib/symbol.py
-Lib/token.py
-Modules/parsermodule.c
diff --git a/Demo/parser/README b/Demo/parser/README
deleted file mode 100644
index f2f18cade5..0000000000
--- a/Demo/parser/README
+++ /dev/null
@@ -1,25 +0,0 @@
-These files are from the large example of using the `parser' module. Refer
-to the Python Library Reference for more information.
-
-Files:
-------
-
- FILES -- list of files associated with the parser module.
-
- README -- this file.
-
- example.py -- module that uses the `parser' module to extract
- information from the parse tree of Python source
- code.
-
- docstring.py -- sample source file containing only a module docstring.
-
- simple.py -- sample source containing a "short form" definition.
-
- source.py -- sample source code used to demonstrate ability to
- handle nested constructs easily using the functions
- and classes in example.py.
-
- test_parser.py program to put the parser module through it's paces.
-
-Enjoy!
diff --git a/Demo/parser/docstring.py b/Demo/parser/docstring.py
deleted file mode 100644
index 45a261b61c..0000000000
--- a/Demo/parser/docstring.py
+++ /dev/null
@@ -1,2 +0,0 @@
-"""Some documentation.
-"""
diff --git a/Demo/parser/example.py b/Demo/parser/example.py
deleted file mode 100644
index 2aa9ec2857..0000000000
--- a/Demo/parser/example.py
+++ /dev/null
@@ -1,190 +0,0 @@
-"""Simple code to extract class & function docstrings from a module.
-
-This code is used as an example in the library reference manual in the
-section on using the parser module. Refer to the manual for a thorough
-discussion of the operation of this code.
-"""
-
-import os
-import parser
-import symbol
-import token
-import types
-
-from types import ListType, TupleType
-
-
-def get_docs(fileName):
- """Retrieve information from the parse tree of a source file.
-
- fileName
- Name of the file to read Python source code from.
- """
- source = open(fileName).read()
- basename = os.path.basename(os.path.splitext(fileName)[0])
- ast = parser.suite(source)
- return ModuleInfo(ast.totuple(), basename)
-
-
-class SuiteInfoBase:
- _docstring = ''
- _name = ''
-
- def __init__(self, tree = None):
- self._class_info = {}
- self._function_info = {}
- if tree:
- self._extract_info(tree)
-
- def _extract_info(self, tree):
- # extract docstring
- if len(tree) == 2:
- found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])
- else:
- found, vars = match(DOCSTRING_STMT_PATTERN, tree[3])
- if found:
- self._docstring = eval(vars['docstring'])
- # discover inner definitions
- for node in tree[1:]:
- found, vars = match(COMPOUND_STMT_PATTERN, node)
- if found:
- cstmt = vars['compound']
- if cstmt[0] == symbol.funcdef:
- name = cstmt[2][1]
- self._function_info[name] = FunctionInfo(cstmt)
- elif cstmt[0] == symbol.classdef:
- name = cstmt[2][1]
- self._class_info[name] = ClassInfo(cstmt)
-
- def get_docstring(self):
- return self._docstring
-
- def get_name(self):
- return self._name
-
- def get_class_names(self):
- return self._class_info.keys()
-
- def get_class_info(self, name):
- return self._class_info[name]
-
- def __getitem__(self, name):
- try:
- return self._class_info[name]
- except KeyError:
- return self._function_info[name]
-
-
-class SuiteFuncInfo:
- # Mixin class providing access to function names and info.
-
- def get_function_names(self):
- return self._function_info.keys()
-
- def get_function_info(self, name):
- return self._function_info[name]
-
-
-class FunctionInfo(SuiteInfoBase, SuiteFuncInfo):
- def __init__(self, tree = None):
- self._name = tree[2][1]
- SuiteInfoBase.__init__(self, tree and tree[-1] or None)
-
-
-class ClassInfo(SuiteInfoBase):
- def __init__(self, tree = None):
- self._name = tree[2][1]
- SuiteInfoBase.__init__(self, tree and tree[-1] or None)
-
- def get_method_names(self):
- return self._function_info.keys()
-
- def get_method_info(self, name):
- return self._function_info[name]
-
-
-class ModuleInfo(SuiteInfoBase, SuiteFuncInfo):
- def __init__(self, tree = None, name = ""):
- self._name = name
- SuiteInfoBase.__init__(self, tree)
- if tree:
- found, vars = match(DOCSTRING_STMT_PATTERN, tree[1])
- if found:
- self._docstring = vars["docstring"]
-
-
-def match(pattern, data, vars=None):
- """Match `data' to `pattern', with variable extraction.
-
- pattern
- Pattern to match against, possibly containing variables.
-
- data
- Data to be checked and against which variables are extracted.
-
- vars
- Dictionary of variables which have already been found. If not
- provided, an empty dictionary is created.
-
- The `pattern' value may contain variables of the form ['varname'] which
- are allowed to match anything. The value that is matched is returned as
- part of a dictionary which maps 'varname' to the matched value. 'varname'
- is not required to be a string object, but using strings makes patterns
- and the code which uses them more readable.
-
- This function returns two values: a boolean indicating whether a match
- was found and a dictionary mapping variable names to their associated
- values.
- """
- if vars is None:
- vars = {}
- if type(pattern) is ListType: # 'variables' are ['varname']
- vars[pattern[0]] = data
- return 1, vars
- if type(pattern) is not TupleType:
- return (pattern == data), vars
- if len(data) != len(pattern):
- return 0, vars
- for pattern, data in map(None, pattern, data):
- same, vars = match(pattern, data, vars)
- if not same:
- break
- return same, vars
-
-
-# This pattern identifies compound statements, allowing them to be readily
-# differentiated from simple statements.
-#
-COMPOUND_STMT_PATTERN = (
- symbol.stmt,
- (symbol.compound_stmt, ['compound'])
- )
-
-
-# This pattern will match a 'stmt' node which *might* represent a docstring;
-# docstrings require that the statement which provides the docstring be the
-# first statement in the class or function, which this pattern does not check.
-#
-DOCSTRING_STMT_PATTERN = (
- symbol.stmt,
- (symbol.simple_stmt,
- (symbol.small_stmt,
- (symbol.expr_stmt,
- (symbol.testlist,
- (symbol.test,
- (symbol.and_test,
- (symbol.not_test,
- (symbol.comparison,
- (symbol.expr,
- (symbol.xor_expr,
- (symbol.and_expr,
- (symbol.shift_expr,
- (symbol.arith_expr,
- (symbol.term,
- (symbol.factor,
- (symbol.power,
- (symbol.atom,
- (token.STRING, ['docstring'])
- )))))))))))))))),
- (token.NEWLINE, '')
- ))
diff --git a/Demo/parser/simple.py b/Demo/parser/simple.py
deleted file mode 100644
index 184e2fe5d0..0000000000
--- a/Demo/parser/simple.py
+++ /dev/null
@@ -1 +0,0 @@
-def f(): "maybe a docstring"
diff --git a/Demo/parser/source.py b/Demo/parser/source.py
deleted file mode 100644
index b90062851f..0000000000
--- a/Demo/parser/source.py
+++ /dev/null
@@ -1,27 +0,0 @@
-"""Exmaple file to be parsed for the parsermodule example.
-
-The classes and functions in this module exist only to exhibit the ability
-of the handling information extraction from nested definitions using parse
-trees. They shouldn't interest you otherwise!
-"""
-
-class Simple:
- "This class does very little."
-
- def method(self):
- "This method does almost nothing."
- return 1
-
- class Nested:
- "This is a nested class."
-
- def nested_method(self):
- "Method of Nested class."
- def nested_function():
- "Function in method of Nested class."
- pass
- return nested_function
-
-def function():
- "This function lives at the module level."
- return 0
diff --git a/Demo/parser/test_parser.py b/Demo/parser/test_parser.py
deleted file mode 100755
index be39bca7f0..0000000000
--- a/Demo/parser/test_parser.py
+++ /dev/null
@@ -1,48 +0,0 @@
-#! /usr/bin/env python
-# (Force the script to use the latest build.)
-#
-# test_parser.py
-
-import parser, traceback
-
-_numFailed = 0
-
-def testChunk(t, fileName):
- global _numFailed
- print '----', fileName,
- try:
- ast = parser.suite(t)
- tup = parser.ast2tuple(ast)
- # this discards the first AST; a huge memory savings when running
- # against a large source file like Tkinter.py.
- ast = None
- new = parser.tuple2ast(tup)
- except parser.ParserError, err:
- print
- print 'parser module raised exception on input file', fileName + ':'
- traceback.print_exc()
- _numFailed = _numFailed + 1
- else:
- if tup != parser.ast2tuple(new):
- print
- print 'parser module failed on input file', fileName
- _numFailed = _numFailed + 1
- else:
- print 'o.k.'
-
-def testFile(fileName):
- t = open(fileName).read()
- testChunk(t, fileName)
-
-def test():
- import sys
- args = sys.argv[1:]
- if not args:
- import glob
- args = glob.glob("*.py")
- args.sort()
- map(testFile, args)
- sys.exit(_numFailed != 0)
-
-if __name__ == '__main__':
- test()
diff --git a/Demo/parser/texipre.dat b/Demo/parser/texipre.dat
deleted file mode 100644
index 8ad03a6175..0000000000
--- a/Demo/parser/texipre.dat
+++ /dev/null
@@ -1,100 +0,0 @@
-\input texinfo @c -*-texinfo-*-
-@c %**start of header
-@setfilename parser.info
-@settitle Python Parser Module Reference
-@setchapternewpage odd
-@footnotestyle end
-@c %**end of header
-
-@ifinfo
-This file describes the interfaces
-published by the optional @code{parser} module and gives examples of
-how they may be used. It contains the same text as the chapter on the
-@code{parser} module in the @cite{Python Library Reference}, but is
-presented as a separate document.
-
-Copyright 1995-1996 by Fred L. Drake, Jr., Reston, Virginia, USA, and
-Virginia Polytechnic Institute and State University, Blacksburg,
-Virginia, USA. Portions of the software copyright 1991-1995 by
-Stichting Mathematisch Centrum, Amsterdam, The Netherlands. Copying is
-permitted under the terms associated with the main Python distribution,
-with the additional restriction that this additional notice be included
-and maintained on all distributed copies.
-
- All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in
-supporting documentation, and that the names of Fred L. Drake, Jr. and
-Virginia Polytechnic Institute and State University not be used in
-advertising or publicity pertaining to distribution of the software
-without specific, written prior permission.
-
-FRED L. DRAKE, JR. AND VIRGINIA POLYTECHNIC INSTITUTE AND STATE
-UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
-INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
-EVENT SHALL FRED L. DRAKE, JR. OR VIRGINIA POLYTECHNIC INSTITUTE AND
-STATE UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
-DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
-PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-@end ifinfo
-
-@titlepage
-@title Python Parser Module Reference
-@author Fred L. Drake, Jr.
-
-@c The following two commands start the copyright page.
-@page
-@vskip 0pt plus 1filll
-Copyright 1995-1996 by Fred L. Drake, Jr., Reston, Virginia, USA, and
-Virginia Polytechnic Institute and State University, Blacksburg,
-Virginia, USA. Portions of the software copyright 1991-1995 by
-Stichting Mathematisch Centrum, Amsterdam, The Netherlands. Copying is
-permitted under the terms associated with the main Python distribution,
-with the additional restriction that this additional notice be included
-and maintained on all distributed copies.
-
-@center All Rights Reserved
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in
-supporting documentation, and that the names of Fred L. Drake, Jr. and
-Virginia Polytechnic Institute and State University not be used in
-advertising or publicity pertaining to distribution of the software
-without specific, written prior permission.
-
-FRED L. DRAKE, JR. AND VIRGINIA POLYTECHNIC INSTITUTE AND STATE
-UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
-INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
-EVENT SHALL FRED L. DRAKE, JR. OR VIRGINIA POLYTECHNIC INSTITUTE AND
-STATE UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
-DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
-PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
-TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-@end titlepage
-
-
-@node Top, Overview, (dir), (dir)
-@top The Python Parser Module
-
-@ifinfo
-This file describes the interfaces
-published by the optional @code{parser} module and gives examples of
-how they may be used. It contains the same text as the chapter on the
-@code{parser} module in the @cite{Python Library Reference}, but is
-presented as a separate document.
-
-This version corresponds to Python version 1.4 (1 Sept. 1996).
-
-@end ifinfo
-
-@c placeholder for the master menu -- patched by texinfo-all-menus-update
-@menu
-@end menu
diff --git a/Demo/pdist/FSProxy.py b/Demo/pdist/FSProxy.py
deleted file mode 100755
index 7510d1e6fd..0000000000
--- a/Demo/pdist/FSProxy.py
+++ /dev/null
@@ -1,322 +0,0 @@
-"""File System Proxy.
-
-Provide an OS-neutral view on a file system, locally or remotely.
-The functionality is geared towards implementing some sort of
-rdist-like utility between a Mac and a UNIX system.
-
-The module defines three classes:
-
-FSProxyLocal -- used for local access
-FSProxyServer -- used on the server side of remote access
-FSProxyClient -- used on the client side of remote access
-
-The remote classes are instantiated with an IP address and an optional
-verbosity flag.
-"""
-
-import server
-import client
-import md5
-import os
-import fnmatch
-from stat import *
-import time
-import fnmatch
-
-if os.name == 'mac':
- import macfs
- maxnamelen = 31
-else:
- macfs = None
- maxnamelen = 255
-
-skipnames = (os.curdir, os.pardir)
-
-
-class FSProxyLocal:
-
- def __init__(self):
- self._dirstack = []
- self._ignore = ['*.pyc'] + self._readignore()
-
- def _close(self):
- while self._dirstack:
- self.back()
-
- def _readignore(self):
- file = self._hide('ignore')
- try:
- f = open(file)
- except IOError:
- file = self._hide('synctree.ignorefiles')
- try:
- f = open(file)
- except IOError:
- return []
- ignore = []
- while 1:
- line = f.readline()
- if not line: break
- if line[-1] == '\n': line = line[:-1]
- ignore.append(line)
- f.close()
- return ignore
-
- def _hidden(self, name):
- if os.name == 'mac':
- return name[0] == '(' and name[-1] == ')'
- else:
- return name[0] == '.'
-
- def _hide(self, name):
- if os.name == 'mac':
- return '(%s)' % name
- else:
- return '.%s' % name
-
- def visible(self, name):
- if len(name) > maxnamelen: return 0
- if name[-1] == '~': return 0
- if name in skipnames: return 0
- if self._hidden(name): return 0
- head, tail = os.path.split(name)
- if head or not tail: return 0
- if macfs:
- if os.path.exists(name) and not os.path.isdir(name):
- try:
- fs = macfs.FSSpec(name)
- c, t = fs.GetCreatorType()
- if t != 'TEXT': return 0
- except macfs.error, msg:
- print "***", name, msg
- return 0
- else:
- if os.path.islink(name): return 0
- if '\0' in open(name, 'rb').read(512): return 0
- for ign in self._ignore:
- if fnmatch.fnmatch(name, ign): return 0
- return 1
-
- def check(self, name):
- if not self.visible(name):
- raise os.error, "protected name %s" % repr(name)
-
- def checkfile(self, name):
- self.check(name)
- if not os.path.isfile(name):
- raise os.error, "not a plain file %s" % repr(name)
-
- def pwd(self):
- return os.getcwd()
-
- def cd(self, name):
- self.check(name)
- save = os.getcwd(), self._ignore
- os.chdir(name)
- self._dirstack.append(save)
- self._ignore = self._ignore + self._readignore()
-
- def back(self):
- if not self._dirstack:
- raise os.error, "empty directory stack"
- dir, ignore = self._dirstack[-1]
- os.chdir(dir)
- del self._dirstack[-1]
- self._ignore = ignore
-
- def _filter(self, files, pat = None):
- if pat:
- def keep(name, pat = pat):
- return fnmatch.fnmatch(name, pat)
- files = filter(keep, files)
- files = filter(self.visible, files)
- files.sort()
- return files
-
- def list(self, pat = None):
- files = os.listdir(os.curdir)
- return self._filter(files, pat)
-
- def listfiles(self, pat = None):
- files = os.listdir(os.curdir)
- files = filter(os.path.isfile, files)
- return self._filter(files, pat)
-
- def listsubdirs(self, pat = None):
- files = os.listdir(os.curdir)
- files = filter(os.path.isdir, files)
- return self._filter(files, pat)
-
- def exists(self, name):
- return self.visible(name) and os.path.exists(name)
-
- def isdir(self, name):
- return self.visible(name) and os.path.isdir(name)
-
- def islink(self, name):
- return self.visible(name) and os.path.islink(name)
-
- def isfile(self, name):
- return self.visible(name) and os.path.isfile(name)
-
- def sum(self, name):
- self.checkfile(name)
- BUFFERSIZE = 1024*8
- f = open(name)
- sum = md5.new()
- while 1:
- buffer = f.read(BUFFERSIZE)
- if not buffer:
- break
- sum.update(buffer)
- return sum.digest()
-
- def size(self, name):
- self.checkfile(name)
- return os.stat(name)[ST_SIZE]
-
- def mtime(self, name):
- self.checkfile(name)
- return time.localtime(os.stat(name)[ST_MTIME])
-
- def stat(self, name):
- self.checkfile(name)
- size = os.stat(name)[ST_SIZE]
- mtime = time.localtime(os.stat(name)[ST_MTIME])
- return size, mtime
-
- def info(self, name):
- sum = self.sum(name)
- size = os.stat(name)[ST_SIZE]
- mtime = time.localtime(os.stat(name)[ST_MTIME])
- return sum, size, mtime
-
- def _list(self, function, list):
- if list is None:
- list = self.listfiles()
- res = []
- for name in list:
- try:
- res.append((name, function(name)))
- except (os.error, IOError):
- res.append((name, None))
- return res
-
- def sumlist(self, list = None):
- return self._list(self.sum, list)
-
- def statlist(self, list = None):
- return self._list(self.stat, list)
-
- def mtimelist(self, list = None):
- return self._list(self.mtime, list)
-
- def sizelist(self, list = None):
- return self._list(self.size, list)
-
- def infolist(self, list = None):
- return self._list(self.info, list)
-
- def _dict(self, function, list):
- if list is None:
- list = self.listfiles()
- dict = {}
- for name in list:
- try:
- dict[name] = function(name)
- except (os.error, IOError):
- pass
- return dict
-
- def sumdict(self, list = None):
- return self.dict(self.sum, list)
-
- def sizedict(self, list = None):
- return self.dict(self.size, list)
-
- def mtimedict(self, list = None):
- return self.dict(self.mtime, list)
-
- def statdict(self, list = None):
- return self.dict(self.stat, list)
-
- def infodict(self, list = None):
- return self._dict(self.info, list)
-
- def read(self, name, offset = 0, length = -1):
- self.checkfile(name)
- f = open(name)
- f.seek(offset)
- if length == 0:
- data = ''
- elif length < 0:
- data = f.read()
- else:
- data = f.read(length)
- f.close()
- return data
-
- def create(self, name):
- self.check(name)
- if os.path.exists(name):
- self.checkfile(name)
- bname = name + '~'
- try:
- os.unlink(bname)
- except os.error:
- pass
- os.rename(name, bname)
- f = open(name, 'w')
- f.close()
-
- def write(self, name, data, offset = 0):
- self.checkfile(name)
- f = open(name, 'r+')
- f.seek(offset)
- f.write(data)
- f.close()
-
- def mkdir(self, name):
- self.check(name)
- os.mkdir(name, 0777)
-
- def rmdir(self, name):
- self.check(name)
- os.rmdir(name)
-
-
-class FSProxyServer(FSProxyLocal, server.Server):
-
- def __init__(self, address, verbose = server.VERBOSE):
- FSProxyLocal.__init__(self)
- server.Server.__init__(self, address, verbose)
-
- def _close(self):
- server.Server._close(self)
- FSProxyLocal._close(self)
-
- def _serve(self):
- server.Server._serve(self)
- # Retreat into start directory
- while self._dirstack: self.back()
-
-
-class FSProxyClient(client.Client):
-
- def __init__(self, address, verbose = client.VERBOSE):
- client.Client.__init__(self, address, verbose)
-
-
-def test():
- import string
- import sys
- if sys.argv[1:]:
- port = string.atoi(sys.argv[1])
- else:
- port = 4127
- proxy = FSProxyServer(('', port))
- proxy._serverloop()
-
-
-if __name__ == '__main__':
- test()
diff --git a/Demo/pdist/RCSProxy.py b/Demo/pdist/RCSProxy.py
deleted file mode 100755
index 7212ca6224..0000000000
--- a/Demo/pdist/RCSProxy.py
+++ /dev/null
@@ -1,198 +0,0 @@
-#! /usr/bin/env python
-
-"""RCS Proxy.
-
-Provide a simplified interface on RCS files, locally or remotely.
-The functionality is geared towards implementing some sort of
-remote CVS like utility. It is modeled after the similar module
-FSProxy.
-
-The module defines two classes:
-
-RCSProxyLocal -- used for local access
-RCSProxyServer -- used on the server side of remote access
-
-The corresponding client class, RCSProxyClient, is defined in module
-rcsclient.
-
-The remote classes are instantiated with an IP address and an optional
-verbosity flag.
-"""
-
-import server
-import md5
-import os
-import fnmatch
-import string
-import tempfile
-import rcslib
-
-
-class DirSupport:
-
- def __init__(self):
- self._dirstack = []
-
- def __del__(self):
- self._close()
-
- def _close(self):
- while self._dirstack:
- self.back()
-
- def pwd(self):
- return os.getcwd()
-
- def cd(self, name):
- save = os.getcwd()
- os.chdir(name)
- self._dirstack.append(save)
-
- def back(self):
- if not self._dirstack:
- raise os.error, "empty directory stack"
- dir = self._dirstack[-1]
- os.chdir(dir)
- del self._dirstack[-1]
-
- def listsubdirs(self, pat = None):
- files = os.listdir(os.curdir)
- files = filter(os.path.isdir, files)
- return self._filter(files, pat)
-
- def isdir(self, name):
- return os.path.isdir(name)
-
- def mkdir(self, name):
- os.mkdir(name, 0777)
-
- def rmdir(self, name):
- os.rmdir(name)
-
-
-class RCSProxyLocal(rcslib.RCS, DirSupport):
-
- def __init__(self):
- rcslib.RCS.__init__(self)
- DirSupport.__init__(self)
-
- def __del__(self):
- DirSupport.__del__(self)
- rcslib.RCS.__del__(self)
-
- def sumlist(self, list = None):
- return self._list(self.sum, list)
-
- def sumdict(self, list = None):
- return self._dict(self.sum, list)
-
- def sum(self, name_rev):
- f = self._open(name_rev)
- BUFFERSIZE = 1024*8
- sum = md5.new()
- while 1:
- buffer = f.read(BUFFERSIZE)
- if not buffer:
- break
- sum.update(buffer)
- self._closepipe(f)
- return sum.digest()
-
- def get(self, name_rev):
- f = self._open(name_rev)
- data = f.read()
- self._closepipe(f)
- return data
-
- def put(self, name_rev, data, message=None):
- name, rev = self._unmangle(name_rev)
- f = open(name, 'w')
- f.write(data)
- f.close()
- self.checkin(name_rev, message)
- self._remove(name)
-
- def _list(self, function, list = None):
- """INTERNAL: apply FUNCTION to all files in LIST.
-
- Return a list of the results.
-
- The list defaults to all files in the directory if None.
-
- """
- if list is None:
- list = self.listfiles()
- res = []
- for name in list:
- try:
- res.append((name, function(name)))
- except (os.error, IOError):
- res.append((name, None))
- return res
-
- def _dict(self, function, list = None):
- """INTERNAL: apply FUNCTION to all files in LIST.
-
- Return a dictionary mapping files to results.
-
- The list defaults to all files in the directory if None.
-
- """
- if list is None:
- list = self.listfiles()
- dict = {}
- for name in list:
- try:
- dict[name] = function(name)
- except (os.error, IOError):
- pass
- return dict
-
-
-class RCSProxyServer(RCSProxyLocal, server.SecureServer):
-
- def __init__(self, address, verbose = server.VERBOSE):
- RCSProxyLocal.__init__(self)
- server.SecureServer.__init__(self, address, verbose)
-
- def _close(self):
- server.SecureServer._close(self)
- RCSProxyLocal._close(self)
-
- def _serve(self):
- server.SecureServer._serve(self)
- # Retreat into start directory
- while self._dirstack: self.back()
-
-
-def test_server():
- import string
- import sys
- if sys.argv[1:]:
- port = string.atoi(sys.argv[1])
- else:
- port = 4127
- proxy = RCSProxyServer(('', port))
- proxy._serverloop()
-
-
-def test():
- import sys
- if not sys.argv[1:] or sys.argv[1] and sys.argv[1][0] in '0123456789':
- test_server()
- sys.exit(0)
- proxy = RCSProxyLocal()
- what = sys.argv[1]
- if hasattr(proxy, what):
- attr = getattr(proxy, what)
- if callable(attr):
- print apply(attr, tuple(sys.argv[2:]))
- else:
- print `attr`
- else:
- print "%s: no such attribute" % what
- sys.exit(2)
-
-
-if __name__ == '__main__':
- test()
diff --git a/Demo/pdist/README b/Demo/pdist/README
deleted file mode 100644
index b3fac24127..0000000000
--- a/Demo/pdist/README
+++ /dev/null
@@ -1,121 +0,0 @@
-Filesystem, RCS and CVS client and server classes
-=================================================
-
-*** See the security warning at the end of this file! ***
-
-This directory contains various modules and classes that support
-remote file system operations.
-
-CVS stuff
----------
-
-rcvs Script to put in your bin directory
-rcvs.py Remote CVS client command line interface
-
-cvslib.py CVS admin files classes (used by rrcs)
-cvslock.py CVS locking algorithms
-
-RCS stuff
----------
-
-rrcs Script to put in your bin directory
-rrcs.py Remote RCS client command line interface
-
-rcsclient.py Return an RCSProxyClient instance
- (has reasonable default server/port/directory)
-
-RCSProxy.py RCS proxy and server classes (on top of rcslib.py)
-
-rcslib.py Local-only RCS base class (affects stdout &
- local work files)
-
-FSProxy stuff
--------------
-
-sumtree.py Old demo for FSProxy
-cmptree.py First FSProxy client (used to sync from the Mac)
-FSProxy.py Filesystem interface classes
-
-Generic client/server stuff
----------------------------
-
-client.py Client class
-server.py Server class
-
-security.py Security mix-in class (not very secure I think)
-
-Other generic stuff
--------------------
-
-cmdfw.py CommandFrameWork class
- (used by rcvs, should be used by rrcs as well)
-
-
-Client/Server operation
------------------------
-
-The Client and Server classes implement a simple-minded RPC protocol,
-using Python's pickle module to transfer arguments, return values and
-exceptions with the most generality. The Server class is instantiated
-with a port number on which it should listen for requests; the Client
-class is instantiated with a host name and a port number where it
-should connect to. Once a client is connected, a TCP connection is
-maintained between client and server.
-
-The Server class currently handles only one connection at a time;
-however it could be rewritten to allow various modes of operations,
-using multiple threads or processes or the select() system call as
-desired to serve multiple clients simultaneously (when using select(),
-still handling one request at a time). This would not require
-rewriting of the Client class. It may also be possible to adapt the
-code to use UDP instead of TCP, but then both classes will have to be
-rewritten (and unless extensive acknowlegements and request serial
-numbers are used, the server should handle duplicate requests, so its
-semantics should be idempotent -- shrudder).
-
-Even though the FSProxy and RCSProxy modules define client classes,
-the client class is fully generic -- what methods it supports is
-determined entirely by the server. The server class, however, must be
-derived from. This is generally done as follows:
-
- from server import Server
- from client import Client
-
- # Define a class that performs the operations locally
- class MyClassLocal:
- def __init__(self): ...
- def _close(self): ...
-
- # Derive a server class using multiple inheritance
- class MyClassServer(MyClassLocal, Server):
- def __init__(self, address):
- # Must initialize MyClassLocal as well as Server
- MyClassLocal.__init__(self)
- Server.__init__(self, address)
- def _close(self):
- Server._close()
- MyClassLocal._close()
-
- # A dummy client class
- class MyClassClient(Client): pass
-
-Note that because MyClassLocal isn't used in the definition of
-MyClassClient, it would actually be better to place it in a separate
-module so the definition of MyClassLocal isn't executed when we only
-instantiate a client.
-
-The modules client and server should probably be renamed to Client and
-Server in order to match the class names.
-
-
-*** Security warning: this version requires that you have a file
-$HOME/.python_keyfile at the server and client side containing two
-comma- separated numbers. The security system at the moment makes no
-guarantees of actuallng being secure -- however it requires that the
-key file exists and contains the same numbers at both ends for this to
-work. (You can specify an alternative keyfile in $PYTHON_KEYFILE).
-Have a look at the Security class in security.py for details;
-basically, if the key file contains (x, y), then the security server
-class chooses a random number z (the challenge) in the range
-10..100000 and the client must be able to produce pow(z, x, y)
-(i.e. z**x mod y).
diff --git a/Demo/pdist/client.py b/Demo/pdist/client.py
deleted file mode 100755
index 3e93f1ce8e..0000000000
--- a/Demo/pdist/client.py
+++ /dev/null
@@ -1,158 +0,0 @@
-"""RPC Client module."""
-
-import sys
-import socket
-import pickle
-import __builtin__
-import os
-
-
-# Default verbosity (0 = silent, 1 = print connections, 2 = print requests too)
-VERBOSE = 1
-
-
-class Client:
-
- """RPC Client class. No need to derive a class -- it's fully generic."""
-
- def __init__(self, address, verbose = VERBOSE):
- self._pre_init(address, verbose)
- self._post_init()
-
- def _pre_init(self, address, verbose = VERBOSE):
- if type(address) == type(0):
- address = ('', address)
- self._address = address
- self._verbose = verbose
- if self._verbose: print "Connecting to %s ..." % repr(address)
- self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self._socket.connect(address)
- if self._verbose: print "Connected."
- self._lastid = 0 # Last id for which a reply has been received
- self._nextid = 1 # Id of next request
- self._replies = {} # Unprocessed replies
- self._rf = self._socket.makefile('r')
- self._wf = self._socket.makefile('w')
-
- def _post_init(self):
- self._methods = self._call('.methods')
-
- def __del__(self):
- self._close()
-
- def _close(self):
- if self._rf: self._rf.close()
- self._rf = None
- if self._wf: self._wf.close()
- self._wf = None
- if self._socket: self._socket.close()
- self._socket = None
-
- def __getattr__(self, name):
- if name in self._methods:
- method = _stub(self, name)
- setattr(self, name, method) # XXX circular reference
- return method
- raise AttributeError, name
-
- def _setverbose(self, verbose):
- self._verbose = verbose
-
- def _call(self, name, *args):
- return self._vcall(name, args)
-
- def _vcall(self, name, args):
- return self._recv(self._vsend(name, args))
-
- def _send(self, name, *args):
- return self._vsend(name, args)
-
- def _send_noreply(self, name, *args):
- return self._vsend(name, args, 0)
-
- def _vsend_noreply(self, name, args):
- return self._vsend(name, args, 0)
-
- def _vsend(self, name, args, wantreply = 1):
- id = self._nextid
- self._nextid = id+1
- if not wantreply: id = -id
- request = (name, args, id)
- if self._verbose > 1: print "sending request: %s" % repr(request)
- wp = pickle.Pickler(self._wf)
- wp.dump(request)
- return id
-
- def _recv(self, id):
- exception, value, rid = self._vrecv(id)
- if rid != id:
- raise RuntimeError, "request/reply id mismatch: %d/%d" % (id, rid)
- if exception is None:
- return value
- x = exception
- if hasattr(__builtin__, exception):
- x = getattr(__builtin__, exception)
- elif exception in ('posix.error', 'mac.error'):
- x = os.error
- if x == exception:
- exception = x
- raise exception, value
-
- def _vrecv(self, id):
- self._flush()
- if self._replies.has_key(id):
- if self._verbose > 1: print "retrieving previous reply, id = %d" % id
- reply = self._replies[id]
- del self._replies[id]
- return reply
- aid = abs(id)
- while 1:
- if self._verbose > 1: print "waiting for reply, id = %d" % id
- rp = pickle.Unpickler(self._rf)
- reply = rp.load()
- del rp
- if self._verbose > 1: print "got reply: %s" % repr(reply)
- rid = reply[2]
- arid = abs(rid)
- if arid == aid:
- if self._verbose > 1: print "got it"
- return reply
- self._replies[rid] = reply
- if arid > aid:
- if self._verbose > 1: print "got higher id, assume all ok"
- return (None, None, id)
-
- def _flush(self):
- self._wf.flush()
-
-
-from security import Security
-
-
-class SecureClient(Client, Security):
-
- def __init__(self, *args):
- import string
- apply(self._pre_init, args)
- Security.__init__(self)
- self._wf.flush()
- line = self._rf.readline()
- challenge = string.atoi(string.strip(line))
- response = self._encode_challenge(challenge)
- line = `long(response)`
- if line[-1] in 'Ll': line = line[:-1]
- self._wf.write(line + '\n')
- self._wf.flush()
- self._post_init()
-
-class _stub:
-
- """Helper class for Client -- each instance serves as a method of the client."""
-
- def __init__(self, client, name):
- self._client = client
- self._name = name
-
- def __call__(self, *args):
- return self._client._vcall(self._name, args)
-
diff --git a/Demo/pdist/cmdfw.py b/Demo/pdist/cmdfw.py
deleted file mode 100755
index a0c6f5d8ec..0000000000
--- a/Demo/pdist/cmdfw.py
+++ /dev/null
@@ -1,144 +0,0 @@
-"Framework for command line interfaces like CVS. See class CmdFrameWork."
-
-
-class CommandFrameWork:
-
- """Framework class for command line interfaces like CVS.
-
- The general command line structure is
-
- command [flags] subcommand [subflags] [argument] ...
-
- There's a class variable GlobalFlags which specifies the
- global flags options. Subcommands are defined by defining
- methods named do_. Flags for the subcommand are
- defined by defining class or instance variables named
- flags_. If there's no command, method default()
- is called. The __doc__ strings for the do_ methods are used
- for the usage message, printed after the general usage message
- which is the class variable UsageMessage. The class variable
- PostUsageMessage is printed after all the do_ methods' __doc__
- strings. The method's return value can be a suggested exit
- status. [XXX Need to rewrite this to clarify it.]
-
- Common usage is to derive a class, instantiate it, and then call its
- run() method; by default this takes its arguments from sys.argv[1:].
- """
-
- UsageMessage = \
- "usage: (name)s [flags] subcommand [subflags] [argument] ..."
-
- PostUsageMessage = None
-
- GlobalFlags = ''
-
- def __init__(self):
- """Constructor, present for completeness."""
- pass
-
- def run(self, args = None):
- """Process flags, subcommand and options, then run it."""
- import getopt, sys
- if args is None: args = sys.argv[1:]
- try:
- opts, args = getopt.getopt(args, self.GlobalFlags)
- except getopt.error, msg:
- return self.usage(msg)
- self.options(opts)
- if not args:
- self.ready()
- return self.default()
- else:
- cmd = args[0]
- mname = 'do_' + cmd
- fname = 'flags_' + cmd
- try:
- method = getattr(self, mname)
- except AttributeError:
- return self.usage("command %s unknown" % `cmd`)
- try:
- flags = getattr(self, fname)
- except AttributeError:
- flags = ''
- try:
- opts, args = getopt.getopt(args[1:], flags)
- except getopt.error, msg:
- return self.usage(
- "subcommand %s: " % cmd + str(msg))
- self.ready()
- return method(opts, args)
-
- def options(self, opts):
- """Process the options retrieved by getopt.
- Override this if you have any options."""
- if opts:
- print "-"*40
- print "Options:"
- for o, a in opts:
- print 'option', o, 'value', `a`
- print "-"*40
-
- def ready(self):
- """Called just before calling the subcommand."""
- pass
-
- def usage(self, msg = None):
- """Print usage message. Return suitable exit code (2)."""
- if msg: print msg
- print self.UsageMessage % {'name': self.__class__.__name__}
- docstrings = {}
- c = self.__class__
- while 1:
- for name in dir(c):
- if name[:3] == 'do_':
- if docstrings.has_key(name):
- continue
- try:
- doc = getattr(c, name).__doc__
- except:
- doc = None
- if doc:
- docstrings[name] = doc
- if not c.__bases__:
- break
- c = c.__bases__[0]
- if docstrings:
- print "where subcommand can be:"
- names = docstrings.keys()
- names.sort()
- for name in names:
- print docstrings[name]
- if self.PostUsageMessage:
- print self.PostUsageMessage
- return 2
-
- def default(self):
- """Default method, called when no subcommand is given.
- You should always override this."""
- print "Nobody expects the Spanish Inquisition!"
-
-
-def test():
- """Test script -- called when this module is run as a script."""
- import sys
- class Hello(CommandFrameWork):
- def do_hello(self, opts, args):
- "hello -- print 'hello world', needs no arguments"
- print "Hello, world"
- x = Hello()
- tests = [
- [],
- ['hello'],
- ['spam'],
- ['-x'],
- ['hello', '-x'],
- None,
- ]
- for t in tests:
- print '-'*10, t, '-'*10
- sts = x.run(t)
- print "Exit status:", `sts`
-
-
-if __name__ == '__main__':
- test()
diff --git a/Demo/pdist/cmptree.py b/Demo/pdist/cmptree.py
deleted file mode 100755
index 7eaa6c3697..0000000000
--- a/Demo/pdist/cmptree.py
+++ /dev/null
@@ -1,208 +0,0 @@
-"""Compare local and remote dictionaries and transfer differing files -- like rdist."""
-
-import sys
-from repr import repr
-import FSProxy
-import time
-import os
-
-def main():
- pwd = os.getcwd()
- s = raw_input("chdir [%s] " % pwd)
- if s:
- os.chdir(s)
- pwd = os.getcwd()
- host = ask("host", 'voorn.cwi.nl')
- port = 4127
- verbose = 1
- mode = ''
- print """\
-Mode should be a string of characters, indicating what to do with differences.
-r - read different files to local file system
-w - write different files to remote file system
-c - create new files, either remote or local
-d - delete disappearing files, either remote or local
-"""
- s = raw_input("mode [%s] " % mode)
- if s: mode = s
- address = (host, port)
- t1 = time.time()
- local = FSProxy.FSProxyLocal()
- remote = FSProxy.FSProxyClient(address, verbose)
- compare(local, remote, mode)
- remote._close()
- local._close()
- t2 = time.time()
- dt = t2-t1
- mins, secs = divmod(dt, 60)
- print mins, "minutes and", round(secs), "seconds"
- raw_input("[Return to exit] ")
-
-def ask(prompt, default):
- s = raw_input("%s [%s] " % (prompt, default))
- return s or default
-
-def askint(prompt, default):
- s = raw_input("%s [%s] " % (prompt, str(default)))
- if s: return string.atoi(s)
- return default
-
-def compare(local, remote, mode):
- print
- print "PWD =", `os.getcwd()`
- sums_id = remote._send('sumlist')
- subdirs_id = remote._send('listsubdirs')
- remote._flush()
- print "calculating local sums ..."
- lsumdict = {}
- for name, info in local.sumlist():
- lsumdict[name] = info
- print "getting remote sums ..."
- sums = remote._recv(sums_id)
- print "got", len(sums)
- rsumdict = {}
- for name, rsum in sums:
- rsumdict[name] = rsum
- if not lsumdict.has_key(name):
- print `name`, "only remote"
- if 'r' in mode and 'c' in mode:
- recvfile(local, remote, name)
- else:
- lsum = lsumdict[name]
- if lsum != rsum:
- print `name`,
- rmtime = remote.mtime(name)
- lmtime = local.mtime(name)
- if rmtime > lmtime:
- print "remote newer",
- if 'r' in mode:
- recvfile(local, remote, name)
- elif lmtime > rmtime:
- print "local newer",
- if 'w' in mode:
- sendfile(local, remote, name)
- else:
- print "same mtime but different sum?!?!",
- print
- for name in lsumdict.keys():
- if not rsumdict.keys():
- print `name`, "only locally",
- fl()
- if 'w' in mode and 'c' in mode:
- sendfile(local, remote, name)
- elif 'r' in mode and 'd' in mode:
- os.unlink(name)
- print "removed."
- print
- print "gettin subdirs ..."
- subdirs = remote._recv(subdirs_id)
- common = []
- for name in subdirs:
- if local.isdir(name):
- print "Common subdirectory", repr(name)
- common.append(name)
- else:
- print "Remote subdirectory", repr(name), "not found locally"
- if 'r' in mode and 'c' in mode:
- pr = "Create local subdirectory %s? [y] " % \
- repr(name)
- if 'y' in mode:
- ok = 'y'
- else:
- ok = ask(pr, "y")
- if ok[:1] in ('y', 'Y'):
- local.mkdir(name)
- print "Subdirectory %s made" % \
- repr(name)
- common.append(name)
- lsubdirs = local.listsubdirs()
- for name in lsubdirs:
- if name not in subdirs:
- print "Local subdirectory", repr(name), "not found remotely"
- for name in common:
- print "Entering subdirectory", repr(name)
- local.cd(name)
- remote.cd(name)
- compare(local, remote, mode)
- remote.back()
- local.back()
-
-def sendfile(local, remote, name):
- try:
- remote.create(name)
- except (IOError, os.error), msg:
- print "cannot create:", msg
- return
-
- print "sending ...",
- fl()
-
- data = open(name).read()
-
- t1 = time.time()
-
- remote._send_noreply('write', name, data)
- remote._flush()
-
- t2 = time.time()
-
- dt = t2-t1
- print len(data), "bytes in", round(dt), "seconds",
- if dt:
- print "i.e.", round(len(data)/dt), "bytes/sec",
- print
-
-def recvfile(local, remote, name):
- ok = 0
- try:
- rv = recvfile_real(local, remote, name)
- ok = 1
- return rv
- finally:
- if not ok:
- print "*** recvfile of %s failed, deleting" % `name`
- local.delete(name)
-
-def recvfile_real(local, remote, name):
- try:
- local.create(name)
- except (IOError, os.error), msg:
- print "cannot create:", msg
- return
-
- print "receiving ...",
- fl()
-
- f = open(name, 'w')
- t1 = time.time()
-
- length = 4*1024
- offset = 0
- id = remote._send('read', name, offset, length)
- remote._flush()
- while 1:
- newoffset = offset + length
- newid = remote._send('read', name, newoffset, length)
- data = remote._recv(id)
- id = newid
- if not data: break
- f.seek(offset)
- f.write(data)
- offset = newoffset
- size = f.tell()
-
- t2 = time.time()
- f.close()
-
- dt = t2-t1
- print size, "bytes in", round(dt), "seconds",
- if dt:
- print "i.e.", int(size/dt), "bytes/sec",
- print
- remote._recv(id) # ignored
-
-def fl():
- sys.stdout.flush()
-
-if __name__ == '__main__':
- main()
diff --git a/Demo/pdist/cvslib.py b/Demo/pdist/cvslib.py
deleted file mode 100755
index 0f689c498b..0000000000
--- a/Demo/pdist/cvslib.py
+++ /dev/null
@@ -1,364 +0,0 @@
-"""Utilities for CVS administration."""
-
-import string
-import os
-import time
-import md5
-import fnmatch
-
-if not hasattr(time, 'timezone'):
- time.timezone = 0
-
-class File:
-
- """Represent a file's status.
-
- Instance variables:
-
- file -- the filename (no slashes), None if uninitialized
- lseen -- true if the data for the local file is up to date
- eseen -- true if the data from the CVS/Entries entry is up to date
- (this implies that the entry must be written back)
- rseen -- true if the data for the remote file is up to date
- proxy -- RCSProxy instance used to contact the server, or None
-
- Note that lseen and rseen don't necessary mean that a local
- or remote file *exists* -- they indicate that we've checked it.
- However, eseen means that this instance corresponds to an
- entry in the CVS/Entries file.
-
- If lseen is true:
-
- lsum -- checksum of the local file, None if no local file
- lctime -- ctime of the local file, None if no local file
- lmtime -- mtime of the local file, None if no local file
-
- If eseen is true:
-
- erev -- revision, None if this is a no revision (not '0')
- enew -- true if this is an uncommitted added file
- edeleted -- true if this is an uncommitted removed file
- ectime -- ctime of last local file corresponding to erev
- emtime -- mtime of last local file corresponding to erev
- extra -- 5th string from CVS/Entries file
-
- If rseen is true:
-
- rrev -- revision of head, None if non-existent
- rsum -- checksum of that revision, Non if non-existent
-
- If eseen and rseen are both true:
-
- esum -- checksum of revision erev, None if no revision
-
- Note
- """
-
- def __init__(self, file = None):
- if file and '/' in file:
- raise ValueError, "no slash allowed in file"
- self.file = file
- self.lseen = self.eseen = self.rseen = 0
- self.proxy = None
-
- def __cmp__(self, other):
- return cmp(self.file, other.file)
-
- def getlocal(self):
- try:
- self.lmtime, self.lctime = os.stat(self.file)[-2:]
- except os.error:
- self.lmtime = self.lctime = self.lsum = None
- else:
- self.lsum = md5.new(open(self.file).read()).digest()
- self.lseen = 1
-
- def getentry(self, line):
- words = string.splitfields(line, '/')
- if self.file and words[1] != self.file:
- raise ValueError, "file name mismatch"
- self.file = words[1]
- self.erev = words[2]
- self.edeleted = 0
- self.enew = 0
- self.ectime = self.emtime = None
- if self.erev[:1] == '-':
- self.edeleted = 1
- self.erev = self.erev[1:]
- if self.erev == '0':
- self.erev = None
- self.enew = 1
- else:
- dates = words[3]
- self.ectime = unctime(dates[:24])
- self.emtime = unctime(dates[25:])
- self.extra = words[4]
- if self.rseen:
- self.getesum()
- self.eseen = 1
-
- def getremote(self, proxy = None):
- if proxy:
- self.proxy = proxy
- try:
- self.rrev = self.proxy.head(self.file)
- except (os.error, IOError):
- self.rrev = None
- if self.rrev:
- self.rsum = self.proxy.sum(self.file)
- else:
- self.rsum = None
- if self.eseen:
- self.getesum()
- self.rseen = 1
-
- def getesum(self):
- if self.erev == self.rrev:
- self.esum = self.rsum
- elif self.erev:
- name = (self.file, self.erev)
- self.esum = self.proxy.sum(name)
- else:
- self.esum = None
-
- def putentry(self):
- """Return a line suitable for inclusion in CVS/Entries.
-
- The returned line is terminated by a newline.
- If no entry should be written for this file,
- return "".
- """
- if not self.eseen:
- return ""
-
- rev = self.erev or '0'
- if self.edeleted:
- rev = '-' + rev
- if self.enew:
- dates = 'Initial ' + self.file
- else:
- dates = gmctime(self.ectime) + ' ' + \
- gmctime(self.emtime)
- return "/%s/%s/%s/%s/\n" % (
- self.file,
- rev,
- dates,
- self.extra)
-
- def report(self):
- print '-'*50
- def r(key, repr=repr, self=self):
- try:
- value = repr(getattr(self, key))
- except AttributeError:
- value = "?"
- print "%-15s:" % key, value
- r("file")
- if self.lseen:
- r("lsum", hexify)
- r("lctime", gmctime)
- r("lmtime", gmctime)
- if self.eseen:
- r("erev")
- r("enew")
- r("edeleted")
- r("ectime", gmctime)
- r("emtime", gmctime)
- if self.rseen:
- r("rrev")
- r("rsum", hexify)
- if self.eseen:
- r("esum", hexify)
-
-
-class CVS:
-
- """Represent the contents of a CVS admin file (and more).
-
- Class variables:
-
- FileClass -- the class to be instantiated for entries
- (this should be derived from class File above)
- IgnoreList -- shell patterns for local files to be ignored
-
- Instance variables:
-
- entries -- a dictionary containing File instances keyed by
- their file name
- proxy -- an RCSProxy instance, or None
- """
-
- FileClass = File
-
- IgnoreList = ['.*', '@*', ',*', '*~', '*.o', '*.a', '*.so', '*.pyc']
-
- def __init__(self):
- self.entries = {}
- self.proxy = None
-
- def setproxy(self, proxy):
- if proxy is self.proxy:
- return
- self.proxy = proxy
- for e in self.entries.values():
- e.rseen = 0
-
- def getentries(self):
- """Read the contents of CVS/Entries"""
- self.entries = {}
- f = self.cvsopen("Entries")
- while 1:
- line = f.readline()
- if not line: break
- e = self.FileClass()
- e.getentry(line)
- self.entries[e.file] = e
- f.close()
-
- def putentries(self):
- """Write CVS/Entries back"""
- f = self.cvsopen("Entries", 'w')
- for e in self.values():
- f.write(e.putentry())
- f.close()
-
- def getlocalfiles(self):
- list = self.entries.keys()
- addlist = os.listdir(os.curdir)
- for name in addlist:
- if name in list:
- continue
- if not self.ignored(name):
- list.append(name)
- list.sort()
- for file in list:
- try:
- e = self.entries[file]
- except KeyError:
- e = self.entries[file] = self.FileClass(file)
- e.getlocal()
-
- def getremotefiles(self, proxy = None):
- if proxy:
- self.proxy = proxy
- if not self.proxy:
- raise RuntimeError, "no RCS proxy"
- addlist = self.proxy.listfiles()
- for file in addlist:
- try:
- e = self.entries[file]
- except KeyError:
- e = self.entries[file] = self.FileClass(file)
- e.getremote(self.proxy)
-
- def report(self):
- for e in self.values():
- e.report()
- print '-'*50
-
- def keys(self):
- keys = self.entries.keys()
- keys.sort()
- return keys
-
- def values(self):
- def value(key, self=self):
- return self.entries[key]
- return map(value, self.keys())
-
- def items(self):
- def item(key, self=self):
- return (key, self.entries[key])
- return map(item, self.keys())
-
- def cvsexists(self, file):
- file = os.path.join("CVS", file)
- return os.path.exists(file)
-
- def cvsopen(self, file, mode = 'r'):
- file = os.path.join("CVS", file)
- if 'r' not in mode:
- self.backup(file)
- return open(file, mode)
-
- def backup(self, file):
- if os.path.isfile(file):
- bfile = file + '~'
- try: os.unlink(bfile)
- except os.error: pass
- os.rename(file, bfile)
-
- def ignored(self, file):
- if os.path.isdir(file): return True
- for pat in self.IgnoreList:
- if fnmatch.fnmatch(file, pat): return True
- return False
-
-
-# hexify and unhexify are useful to print MD5 checksums in hex format
-
-hexify_format = '%02x' * 16
-def hexify(sum):
- "Return a hex representation of a 16-byte string (e.g. an MD5 digest)"
- if sum is None:
- return "None"
- return hexify_format % tuple(map(ord, sum))
-
-def unhexify(hexsum):
- "Return the original from a hexified string"
- if hexsum == "None":
- return None
- sum = ''
- for i in range(0, len(hexsum), 2):
- sum = sum + chr(string.atoi(hexsum[i:i+2], 16))
- return sum
-
-
-unctime_monthmap = {}
-def unctime(date):
- if date == "None": return None
- if not unctime_monthmap:
- months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
- 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
- i = 0
- for m in months:
- i = i+1
- unctime_monthmap[m] = i
- words = string.split(date) # Day Mon DD HH:MM:SS YEAR
- year = string.atoi(words[4])
- month = unctime_monthmap[words[1]]
- day = string.atoi(words[2])
- [hh, mm, ss] = map(string.atoi, string.splitfields(words[3], ':'))
- ss = ss - time.timezone
- return time.mktime((year, month, day, hh, mm, ss, 0, 0, 0))
-
-def gmctime(t):
- if t is None: return "None"
- return time.asctime(time.gmtime(t))
-
-def test_unctime():
- now = int(time.time())
- t = time.gmtime(now)
- at = time.asctime(t)
- print 'GMT', now, at
- print 'timezone', time.timezone
- print 'local', time.ctime(now)
- u = unctime(at)
- print 'unctime()', u
- gu = time.gmtime(u)
- print '->', gu
- print time.asctime(gu)
-
-def test():
- x = CVS()
- x.getentries()
- x.getlocalfiles()
-## x.report()
- import rcsclient
- proxy = rcsclient.openrcsclient()
- x.getremotefiles(proxy)
- x.report()
-
-
-if __name__ == "__main__":
- test()
diff --git a/Demo/pdist/cvslock.py b/Demo/pdist/cvslock.py
deleted file mode 100755
index a421e1a943..0000000000
--- a/Demo/pdist/cvslock.py
+++ /dev/null
@@ -1,280 +0,0 @@
-"""CVS locking algorithm.
-
-CVS locking strategy
-====================
-
-As reverse engineered from the CVS 1.3 sources (file lock.c):
-
-- Locking is done on a per repository basis (but a process can hold
-write locks for multiple directories); all lock files are placed in
-the repository and have names beginning with "#cvs.".
-
-- Before even attempting to lock, a file "#cvs.tfl." is created
-(and removed again), to test that we can write the repository. [The
-algorithm can still be fooled (1) if the repository's mode is changed
-while attempting to lock; (2) if this file exists and is writable but
-the directory is not.]
-
-- While creating the actual read/write lock files (which may exist for
-a long time), a "meta-lock" is held. The meta-lock is a directory
-named "#cvs.lock" in the repository. The meta-lock is also held while
-a write lock is held.
-
-- To set a read lock:
-
- - acquire the meta-lock
- - create the file "#cvs.rfl."
- - release the meta-lock
-
-- To set a write lock:
-
- - acquire the meta-lock
- - check that there are no files called "#cvs.rfl.*"
- - if there are, release the meta-lock, sleep, try again
- - create the file "#cvs.wfl."
-
-- To release a write lock:
-
- - remove the file "#cvs.wfl."
- - rmdir the meta-lock
-
-- To release a read lock:
-
- - remove the file "#cvs.rfl."
-
-
-Additional notes
-----------------
-
-- A process should read-lock at most one repository at a time.
-
-- A process may write-lock as many repositories as it wishes (to avoid
-deadlocks, I presume it should always lock them top-down in the
-directory hierarchy).
-
-- A process should make sure it removes all its lock files and
-directories when it crashes.
-
-- Limitation: one user id should not be committing files into the same
-repository at the same time.
-
-
-Turn this into Python code
---------------------------
-
-rl = ReadLock(repository, waittime)
-
-wl = WriteLock(repository, waittime)
-
-list = MultipleWriteLock([repository1, repository2, ...], waittime)
-
-"""
-
-
-import os
-import time
-import stat
-import pwd
-
-
-# Default wait time
-DELAY = 10
-
-
-# XXX This should be the same on all Unix versions
-EEXIST = 17
-
-
-# Files used for locking (must match cvs.h in the CVS sources)
-CVSLCK = "#cvs.lck"
-CVSRFL = "#cvs.rfl."
-CVSWFL = "#cvs.wfl."
-
-
-class Error:
-
- def __init__(self, msg):
- self.msg = msg
-
- def __repr__(self):
- return repr(self.msg)
-
- def __str__(self):
- return str(self.msg)
-
-
-class Locked(Error):
- pass
-
-
-class Lock:
-
- def __init__(self, repository = ".", delay = DELAY):
- self.repository = repository
- self.delay = delay
- self.lockdir = None
- self.lockfile = None
- pid = `os.getpid()`
- self.cvslck = self.join(CVSLCK)
- self.cvsrfl = self.join(CVSRFL + pid)
- self.cvswfl = self.join(CVSWFL + pid)
-
- def __del__(self):
- print "__del__"
- self.unlock()
-
- def setlockdir(self):
- while 1:
- try:
- self.lockdir = self.cvslck
- os.mkdir(self.cvslck, 0777)
- return
- except os.error, msg:
- self.lockdir = None
- if msg[0] == EEXIST:
- try:
- st = os.stat(self.cvslck)
- except os.error:
- continue
- self.sleep(st)
- continue
- raise Error("failed to lock %s: %s" % (
- self.repository, msg))
-
- def unlock(self):
- self.unlockfile()
- self.unlockdir()
-
- def unlockfile(self):
- if self.lockfile:
- print "unlink", self.lockfile
- try:
- os.unlink(self.lockfile)
- except os.error:
- pass
- self.lockfile = None
-
- def unlockdir(self):
- if self.lockdir:
- print "rmdir", self.lockdir
- try:
- os.rmdir(self.lockdir)
- except os.error:
- pass
- self.lockdir = None
-
- def sleep(self, st):
- sleep(st, self.repository, self.delay)
-
- def join(self, name):
- return os.path.join(self.repository, name)
-
-
-def sleep(st, repository, delay):
- if delay <= 0:
- raise Locked(st)
- uid = st[stat.ST_UID]
- try:
- pwent = pwd.getpwuid(uid)
- user = pwent[0]
- except KeyError:
- user = "uid %d" % uid
- print "[%s]" % time.ctime(time.time())[11:19],
- print "Waiting for %s's lock in" % user, repository
- time.sleep(delay)
-
-
-class ReadLock(Lock):
-
- def __init__(self, repository, delay = DELAY):
- Lock.__init__(self, repository, delay)
- ok = 0
- try:
- self.setlockdir()
- self.lockfile = self.cvsrfl
- fp = open(self.lockfile, 'w')
- fp.close()
- ok = 1
- finally:
- if not ok:
- self.unlockfile()
- self.unlockdir()
-
-
-class WriteLock(Lock):
-
- def __init__(self, repository, delay = DELAY):
- Lock.__init__(self, repository, delay)
- self.setlockdir()
- while 1:
- uid = self.readers_exist()
- if not uid:
- break
- self.unlockdir()
- self.sleep(uid)
- self.lockfile = self.cvswfl
- fp = open(self.lockfile, 'w')
- fp.close()
-
- def readers_exist(self):
- n = len(CVSRFL)
- for name in os.listdir(self.repository):
- if name[:n] == CVSRFL:
- try:
- st = os.stat(self.join(name))
- except os.error:
- continue
- return st
- return None
-
-
-def MultipleWriteLock(repositories, delay = DELAY):
- while 1:
- locks = []
- for r in repositories:
- try:
- locks.append(WriteLock(r, 0))
- except Locked, instance:
- del locks
- break
- else:
- break
- sleep(instance.msg, r, delay)
- return list
-
-
-def test():
- import sys
- if sys.argv[1:]:
- repository = sys.argv[1]
- else:
- repository = "."
- rl = None
- wl = None
- try:
- print "attempting write lock ..."
- wl = WriteLock(repository)
- print "got it."
- wl.unlock()
- print "attempting read lock ..."
- rl = ReadLock(repository)
- print "got it."
- rl.unlock()
- finally:
- print [1]
- sys.exc_traceback = None
- print [2]
- if rl:
- rl.unlock()
- print [3]
- if wl:
- wl.unlock()
- print [4]
- rl = None
- print [5]
- wl = None
- print [6]
-
-
-if __name__ == '__main__':
- test()
diff --git a/Demo/pdist/mac.py b/Demo/pdist/mac.py
deleted file mode 100755
index 516ee153e4..0000000000
--- a/Demo/pdist/mac.py
+++ /dev/null
@@ -1,19 +0,0 @@
-import sys
-import string
-import rcvs
-
-def main():
- while 1:
- try:
- line = raw_input('$ ')
- except EOFError:
- break
- words = string.split(line)
- if not words:
- continue
- if words[0] != 'rcvs':
- words.insert(0, 'rcvs')
- sys.argv = words
- rcvs.main()
-
-main()
diff --git a/Demo/pdist/makechangelog.py b/Demo/pdist/makechangelog.py
deleted file mode 100755
index b26f30b3a0..0000000000
--- a/Demo/pdist/makechangelog.py
+++ /dev/null
@@ -1,109 +0,0 @@
-#! /usr/bin/env python
-
-"""Turn a pile of RCS log output into ChangeLog file entries.
-
-"""
-
-import sys
-import string
-import regex
-import getopt
-import time
-
-def main():
- args = sys.argv[1:]
- opts, args = getopt.getopt(args, 'p:')
- prefix = ''
- for o, a in opts:
- if p == '-p': prefix = a
-
- f = sys.stdin
- allrevs = []
- while 1:
- file = getnextfile(f)
- if not file: break
- revs = []
- while 1:
- rev = getnextrev(f, file)
- if not rev:
- break
- revs.append(rev)
- if revs:
- allrevs[len(allrevs):] = revs
- allrevs.sort()
- allrevs.reverse()
- for rev in allrevs:
- formatrev(rev, prefix)
-
-parsedateprog = regex.compile(
- '^date: \([0-9]+\)/\([0-9]+\)/\([0-9]+\) ' +
- '\([0-9]+\):\([0-9]+\):\([0-9]+\); author: \([^ ;]+\)')
-
-authormap = {
- 'guido': 'Guido van Rossum ',
- 'jack': 'Jack Jansen ',
- 'sjoerd': 'Sjoerd Mullender ',
- }
-
-def formatrev(rev, prefix):
- dateline, file, revline, log = rev
- if parsedateprog.match(dateline) >= 0:
- fields = parsedateprog.group(1, 2, 3, 4, 5, 6)
- author = parsedateprog.group(7)
- if authormap.has_key(author): author = authormap[author]
- tfields = map(string.atoi, fields) + [0, 0, 0]
- tfields[5] = tfields[5] - time.timezone
- t = time.mktime(tuple(tfields))
- print time.ctime(t), '', author
- words = string.split(log)
- words[:0] = ['*', prefix + file + ':']
- maxcol = 72-8
- col = maxcol
- for word in words:
- if col > 0 and col + len(word) >= maxcol:
- print
- print '\t' + word,
- col = -1
- else:
- print word,
- col = col + 1 + len(word)
- print
- print
-
-startprog = regex.compile("^Working file: \(.*\)$")
-
-def getnextfile(f):
- while 1:
- line = f.readline()
- if not line: return None
- if startprog.match(line) >= 0:
- file = startprog.group(1)
- # Skip until first revision
- while 1:
- line = f.readline()
- if not line: return None
- if line[:10] == '='*10: return None
- if line[:10] == '-'*10: break
-## print "Skipped", line,
- return file
-## else:
-## print "Ignored", line,
-
-def getnextrev(f, file):
- # This is called when we are positioned just after a '---' separator
- revline = f.readline()
- dateline = f.readline()
- log = ''
- while 1:
- line = f.readline()
- if not line: break
- if line[:10] == '='*10:
- # Ignore the *last* log entry for each file since it
- # is the revision since which we are logging.
- return None
- if line[:10] == '-'*10: break
- log = log + line
- return dateline, file, revline, log
-
-if __name__ == '__main__':
- main()
diff --git a/Demo/pdist/rcsbump b/Demo/pdist/rcsbump
deleted file mode 100755
index e4e9ed558d..0000000000
--- a/Demo/pdist/rcsbump
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/usr/bin/env python
-# -*- python -*-
-#
-# guido's version, from rcsbump,v 1.2 1995/06/22 21:27:27 bwarsaw Exp
-#
-# Python script for bumping up an RCS major revision number.
-
-import sys
-import regex
-import rcslib
-import string
-
-WITHLOCK = 1
-majorrev_re = regex.compile('^[0-9]+')
-
-dir = rcslib.RCS()
-
-if sys.argv[1:]:
- files = sys.argv[1:]
-else:
- files = dir.listfiles()
-
-for file in files:
- # get the major revnumber of the file
- headbranch = dir.info(file)['head']
- majorrev_re.match(headbranch)
- majorrev = string.atoi(majorrev_re.group(0)) + 1
-
- if not dir.islocked(file):
- dir.checkout(file, WITHLOCK)
-
- msg = "Bumping major revision number (to %d)" % majorrev
- dir.checkin((file, "%s.0" % majorrev), msg, "-f")
diff --git a/Demo/pdist/rcsclient.py b/Demo/pdist/rcsclient.py
deleted file mode 100755
index 5d88a57981..0000000000
--- a/Demo/pdist/rcsclient.py
+++ /dev/null
@@ -1,71 +0,0 @@
-"""Customize this file to change the default client etc.
-
-(In general, it is probably be better to make local operation the
-default and to require something like an RCSSERVER environment
-variable to enable remote operation.)
-
-"""
-
-import string
-import os
-
-# These defaults don't belong here -- they should be taken from the
-# environment or from a hidden file in the current directory
-
-HOST = 'voorn.cwi.nl'
-PORT = 4127
-VERBOSE = 1
-LOCAL = 0
-
-import client
-
-
-class RCSProxyClient(client.SecureClient):
-
- def __init__(self, address, verbose = client.VERBOSE):
- client.SecureClient.__init__(self, address, verbose)
-
-
-def openrcsclient(opts = []):
- "open an RCSProxy client based on a list of options returned by getopt"
- import RCSProxy
- host = HOST
- port = PORT
- verbose = VERBOSE
- local = LOCAL
- directory = None
- for o, a in opts:
- if o == '-h':
- host = a
- if ':' in host:
- i = string.find(host, ':')
- host, p = host[:i], host[i+1:]
- if p:
- port = string.atoi(p)
- if o == '-p':
- port = string.atoi(a)
- if o == '-d':
- directory = a
- if o == '-v':
- verbose = verbose + 1
- if o == '-q':
- verbose = 0
- if o == '-L':
- local = 1
- if local:
- import RCSProxy
- x = RCSProxy.RCSProxyLocal()
- else:
- address = (host, port)
- x = RCSProxyClient(address, verbose)
- if not directory:
- try:
- directory = open(os.path.join("CVS", "Repository")).readline()
- except IOError:
- pass
- else:
- if directory[-1] == '\n':
- directory = directory[:-1]
- if directory:
- x.cd(directory)
- return x
diff --git a/Demo/pdist/rcslib.py b/Demo/pdist/rcslib.py
deleted file mode 100755
index 4e72766d24..0000000000
--- a/Demo/pdist/rcslib.py
+++ /dev/null
@@ -1,334 +0,0 @@
-"""RCS interface module.
-
-Defines the class RCS, which represents a directory with rcs version
-files and (possibly) corresponding work files.
-
-"""
-
-
-import fnmatch
-import os
-import regsub
-import string
-import tempfile
-
-
-class RCS:
-
- """RCS interface class (local filesystem version).
-
- An instance of this class represents a directory with rcs version
- files and (possible) corresponding work files.
-
- Methods provide access to most rcs operations such as
- checkin/checkout, access to the rcs metadata (revisions, logs,
- branches etc.) as well as some filesystem operations such as
- listing all rcs version files.
-
- XXX BUGS / PROBLEMS
-
- - The instance always represents the current directory so it's not
- very useful to have more than one instance around simultaneously
-
- """
-
- # Characters allowed in work file names
- okchars = string.ascii_letters + string.digits + '-_=+'
-
- def __init__(self):
- """Constructor."""
- pass
-
- def __del__(self):
- """Destructor."""
- pass
-
- # --- Informational methods about a single file/revision ---
-
- def log(self, name_rev, otherflags = ''):
- """Return the full log text for NAME_REV as a string.
-
- Optional OTHERFLAGS are passed to rlog.
-
- """
- f = self._open(name_rev, 'rlog ' + otherflags)
- data = f.read()
- status = self._closepipe(f)
- if status:
- data = data + "%s: %s" % status
- elif data[-1] == '\n':
- data = data[:-1]
- return data
-
- def head(self, name_rev):
- """Return the head revision for NAME_REV"""
- dict = self.info(name_rev)
- return dict['head']
-
- def info(self, name_rev):
- """Return a dictionary of info (from rlog -h) for NAME_REV
-
- The dictionary's keys are the keywords that rlog prints
- (e.g. 'head' and its values are the corresponding data
- (e.g. '1.3').
-
- XXX symbolic names and locks are not returned
-
- """
- f = self._open(name_rev, 'rlog -h')
- dict = {}
- while 1:
- line = f.readline()
- if not line: break
- if line[0] == '\t':
- # XXX could be a lock or symbolic name
- # Anything else?
- continue
- i = string.find(line, ':')
- if i > 0:
- key, value = line[:i], string.strip(line[i+1:])
- dict[key] = value
- status = self._closepipe(f)
- if status:
- raise IOError, status
- return dict
-
- # --- Methods that change files ---
-
- def lock(self, name_rev):
- """Set an rcs lock on NAME_REV."""
- name, rev = self.checkfile(name_rev)
- cmd = "rcs -l%s %s" % (rev, name)
- return self._system(cmd)
-
- def unlock(self, name_rev):
- """Clear an rcs lock on NAME_REV."""
- name, rev = self.checkfile(name_rev)
- cmd = "rcs -u%s %s" % (rev, name)
- return self._system(cmd)
-
- def checkout(self, name_rev, withlock=0, otherflags=""):
- """Check out NAME_REV to its work file.
-
- If optional WITHLOCK is set, check out locked, else unlocked.
-
- The optional OTHERFLAGS is passed to co without
- interpretation.
-
- Any output from co goes to directly to stdout.
-
- """
- name, rev = self.checkfile(name_rev)
- if withlock: lockflag = "-l"
- else: lockflag = "-u"
- cmd = 'co %s%s %s %s' % (lockflag, rev, otherflags, name)
- return self._system(cmd)
-
- def checkin(self, name_rev, message=None, otherflags=""):
- """Check in NAME_REV from its work file.
-
- The optional MESSAGE argument becomes the checkin message
- (default "" if None); or the file description if this is
- a new file.
-
- The optional OTHERFLAGS argument is passed to ci without
- interpretation.
-
- Any output from ci goes to directly to stdout.
-
- """
- name, rev = self._unmangle(name_rev)
- new = not self.isvalid(name)
- if not message: message = ""
- if message and message[-1] != '\n':
- message = message + '\n'
- lockflag = "-u"
- if new:
- f = tempfile.NamedTemporaryFile()
- f.write(message)
- f.flush()
- cmd = 'ci %s%s -t%s %s %s' % \
- (lockflag, rev, f.name, otherflags, name)
- else:
- message = regsub.gsub('\([\\"$`]\)', '\\\\\\1', message)
- cmd = 'ci %s%s -m"%s" %s %s' % \
- (lockflag, rev, message, otherflags, name)
- return self._system(cmd)
-
- # --- Exported support methods ---
-
- def listfiles(self, pat = None):
- """Return a list of all version files matching optional PATTERN."""
- files = os.listdir(os.curdir)
- files = filter(self._isrcs, files)
- if os.path.isdir('RCS'):
- files2 = os.listdir('RCS')
- files2 = filter(self._isrcs, files2)
- files = files + files2
- files = map(self.realname, files)
- return self._filter(files, pat)
-
- def isvalid(self, name):
- """Test whether NAME has a version file associated."""
- namev = self.rcsname(name)
- return (os.path.isfile(namev) or
- os.path.isfile(os.path.join('RCS', namev)))
-
- def rcsname(self, name):
- """Return the pathname of the version file for NAME.
-
- The argument can be a work file name or a version file name.
- If the version file does not exist, the name of the version
- file that would be created by "ci" is returned.
-
- """
- if self._isrcs(name): namev = name
- else: namev = name + ',v'
- if os.path.isfile(namev): return namev
- namev = os.path.join('RCS', os.path.basename(namev))
- if os.path.isfile(namev): return namev
- if os.path.isdir('RCS'):
- return os.path.join('RCS', namev)
- else:
- return namev
-
- def realname(self, namev):
- """Return the pathname of the work file for NAME.
-
- The argument can be a work file name or a version file name.
- If the work file does not exist, the name of the work file
- that would be created by "co" is returned.
-
- """
- if self._isrcs(namev): name = namev[:-2]
- else: name = namev
- if os.path.isfile(name): return name
- name = os.path.basename(name)
- return name
-
- def islocked(self, name_rev):
- """Test whether FILE (which must have a version file) is locked.
-
- XXX This does not tell you which revision number is locked and
- ignores any revision you may pass in (by virtue of using rlog
- -L -R).
-
- """
- f = self._open(name_rev, 'rlog -L -R')
- line = f.readline()
- status = self._closepipe(f)
- if status:
- raise IOError, status
- if not line: return None
- if line[-1] == '\n':
- line = line[:-1]
- return self.realname(name_rev) == self.realname(line)
-
- def checkfile(self, name_rev):
- """Normalize NAME_REV into a (NAME, REV) tuple.
-
- Raise an exception if there is no corresponding version file.
-
- """
- name, rev = self._unmangle(name_rev)
- if not self.isvalid(name):
- raise os.error, 'not an rcs file %s' % `name`
- return name, rev
-
- # --- Internal methods ---
-
- def _open(self, name_rev, cmd = 'co -p', rflag = '-r'):
- """INTERNAL: open a read pipe to NAME_REV using optional COMMAND.
-
- Optional FLAG is used to indicate the revision (default -r).
-
- Default COMMAND is "co -p".
-
- Return a file object connected by a pipe to the command's
- output.
-
- """
- name, rev = self.checkfile(name_rev)
- namev = self.rcsname(name)
- if rev:
- cmd = cmd + ' ' + rflag + rev
- return os.popen("%s %s" % (cmd, `namev`))
-
- def _unmangle(self, name_rev):
- """INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple.
-
- Raise an exception if NAME contains invalid characters.
-
- A NAME_REV argument is either NAME string (implying REV='') or
- a tuple of the form (NAME, REV).
-
- """
- if type(name_rev) == type(''):
- name_rev = name, rev = name_rev, ''
- else:
- name, rev = name_rev
- for c in rev:
- if c not in self.okchars:
- raise ValueError, "bad char in rev"
- return name_rev
-
- def _closepipe(self, f):
- """INTERNAL: Close PIPE and print its exit status if nonzero."""
- sts = f.close()
- if not sts: return None
- detail, reason = divmod(sts, 256)
- if reason == 0: return 'exit', detail # Exit status
- signal = reason&0x7F
- if signal == 0x7F:
- code = 'stopped'
- signal = detail
- else:
- code = 'killed'
- if reason&0x80:
- code = code + '(coredump)'
- return code, signal
-
- def _system(self, cmd):
- """INTERNAL: run COMMAND in a subshell.
-
- Standard input for the command is taken from /dev/null.
-
- Raise IOError when the exit status is not zero.
-
- Return whatever the calling method should return; normally
- None.
-
- A derived class may override this method and redefine it to
- capture stdout/stderr of the command and return it.
-
- """
- cmd = cmd + " > ")
- sys.stderr.flush()
- line = sys.stdin.readline()
- if not line or line == '.\n': break
- message = message + line
- return message
-
-def remove(fn):
- try:
- os.unlink(fn)
- except os.error:
- pass
-
-commands = {
- 'ci': ('', checkin),
- 'put': ('', checkin),
- 'co': ('', checkout),
- 'get': ('', checkout),
- 'info': ('', info),
- 'head': ('', head),
- 'list': ('', list),
- 'lock': ('', lock),
- 'unlock': ('', unlock),
- 'log': ('bhLRtd:l:r:s:w:V:', log),
- 'diff': ('c', diff),
- }
-
-if __name__ == '__main__':
- main()
diff --git a/Demo/pdist/security.py b/Demo/pdist/security.py
deleted file mode 100755
index 0ffd511a07..0000000000
--- a/Demo/pdist/security.py
+++ /dev/null
@@ -1,33 +0,0 @@
-class Security:
-
- def __init__(self):
- import os
- env = os.environ
- if env.has_key('PYTHON_KEYFILE'):
- keyfile = env['PYTHON_KEYFILE']
- else:
- keyfile = '.python_keyfile'
- if env.has_key('HOME'):
- keyfile = os.path.join(env['HOME'], keyfile)
- if not os.path.exists(keyfile):
- import sys
- for dir in sys.path:
- kf = os.path.join(dir, keyfile)
- if os.path.exists(kf):
- keyfile = kf
- break
- try:
- self._key = eval(open(keyfile).readline())
- except IOError:
- raise IOError, "python keyfile %s: cannot open" % keyfile
-
- def _generate_challenge(self):
- import random
- return random.randint(100, 100000)
-
- def _compare_challenge_response(self, challenge, response):
- return self._encode_challenge(challenge) == response
-
- def _encode_challenge(self, challenge):
- p, m = self._key
- return pow(long(challenge), p, m)
diff --git a/Demo/pdist/server.py b/Demo/pdist/server.py
deleted file mode 100755
index 423d583007..0000000000
--- a/Demo/pdist/server.py
+++ /dev/null
@@ -1,145 +0,0 @@
-"""RPC Server module."""
-
-import sys
-import socket
-import pickle
-from fnmatch import fnmatch
-from repr import repr
-
-
-# Default verbosity (0 = silent, 1 = print connections, 2 = print requests too)
-VERBOSE = 1
-
-
-class Server:
-
- """RPC Server class. Derive a class to implement a particular service."""
-
- def __init__(self, address, verbose = VERBOSE):
- if type(address) == type(0):
- address = ('', address)
- self._address = address
- self._verbose = verbose
- self._socket = None
- self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self._socket.bind(address)
- self._socket.listen(1)
- self._listening = 1
-
- def _setverbose(self, verbose):
- self._verbose = verbose
-
- def __del__(self):
- self._close()
-
- def _close(self):
- self._listening = 0
- if self._socket:
- self._socket.close()
- self._socket = None
-
- def _serverloop(self):
- while self._listening:
- self._serve()
-
- def _serve(self):
- if self._verbose: print "Wait for connection ..."
- conn, address = self._socket.accept()
- if self._verbose: print "Accepted connection from %s" % repr(address)
- if not self._verify(conn, address):
- print "*** Connection from %s refused" % repr(address)
- conn.close()
- return
- rf = conn.makefile('r')
- wf = conn.makefile('w')
- ok = 1
- while ok:
- wf.flush()
- if self._verbose > 1: print "Wait for next request ..."
- ok = self._dorequest(rf, wf)
-
- _valid = ['192.16.201.*', '192.16.197.*', '132.151.1.*', '129.6.64.*']
-
- def _verify(self, conn, address):
- host, port = address
- for pat in self._valid:
- if fnmatch(host, pat): return 1
- return 0
-
- def _dorequest(self, rf, wf):
- rp = pickle.Unpickler(rf)
- try:
- request = rp.load()
- except EOFError:
- return 0
- if self._verbose > 1: print "Got request: %s" % repr(request)
- try:
- methodname, args, id = request
- if '.' in methodname:
- reply = (None, self._special(methodname, args), id)
- elif methodname[0] == '_':
- raise NameError, "illegal method name %s" % repr(methodname)
- else:
- method = getattr(self, methodname)
- reply = (None, apply(method, args), id)
- except:
- reply = (sys.exc_type, sys.exc_value, id)
- if id < 0 and reply[:2] == (None, None):
- if self._verbose > 1: print "Suppress reply"
- return 1
- if self._verbose > 1: print "Send reply: %s" % repr(reply)
- wp = pickle.Pickler(wf)
- wp.dump(reply)
- return 1
-
- def _special(self, methodname, args):
- if methodname == '.methods':
- if not hasattr(self, '_methods'):
- self._methods = tuple(self._listmethods())
- return self._methods
- raise NameError, "unrecognized special method name %s" % repr(methodname)
-
- def _listmethods(self, cl=None):
- if not cl: cl = self.__class__
- names = cl.__dict__.keys()
- names = filter(lambda x: x[0] != '_', names)
- names.sort()
- for base in cl.__bases__:
- basenames = self._listmethods(base)
- basenames = filter(lambda x, names=names: x not in names, basenames)
- names[len(names):] = basenames
- return names
-
-
-from security import Security
-
-
-class SecureServer(Server, Security):
-
- def __init__(self, *args):
- apply(Server.__init__, (self,) + args)
- Security.__init__(self)
-
- def _verify(self, conn, address):
- import string
- challenge = self._generate_challenge()
- conn.send("%d\n" % challenge)
- response = ""
- while "\n" not in response and len(response) < 100:
- data = conn.recv(100)
- if not data:
- break
- response = response + data
- try:
- response = string.atol(string.strip(response))
- except string.atol_error:
- if self._verbose > 0:
- print "Invalid response syntax", `response`
- return 0
- if not self._compare_challenge_response(challenge, response):
- if self._verbose > 0:
- print "Invalid response value", `response`
- return 0
- if self._verbose > 1:
- print "Response matches challenge. Go ahead!"
- return 1
diff --git a/Demo/pdist/sumtree.py b/Demo/pdist/sumtree.py
deleted file mode 100755
index 92c1fd0552..0000000000
--- a/Demo/pdist/sumtree.py
+++ /dev/null
@@ -1,24 +0,0 @@
-import time
-import FSProxy
-
-def main():
- t1 = time.time()
- #proxy = FSProxy.FSProxyClient(('voorn.cwi.nl', 4127))
- proxy = FSProxy.FSProxyLocal()
- sumtree(proxy)
- proxy._close()
- t2 = time.time()
- print t2-t1, "seconds"
- raw_input("[Return to exit] ")
-
-def sumtree(proxy):
- print "PWD =", proxy.pwd()
- files = proxy.listfiles()
- proxy.infolist(files)
- subdirs = proxy.listsubdirs()
- for name in subdirs:
- proxy.cd(name)
- sumtree(proxy)
- proxy.back()
-
-main()
diff --git a/Demo/pysvr/Makefile b/Demo/pysvr/Makefile
deleted file mode 100644
index b4b9f3e115..0000000000
--- a/Demo/pysvr/Makefile
+++ /dev/null
@@ -1,57 +0,0 @@
-# Makefile for 'pysvr' application embedding Python.
-# Tailored for Python 1.5a3 or later.
-# Some details are specific for Solaris or CNRI.
-# Also see ## comments for tailoring.
-
-# Which C compiler
-CC=gcc
-##PURIFY=/usr/local/pure/purify
-LINKCC=$(PURIFY) $(CC)
-
-# Optimization preferences
-OPT=-g
-
-# Which Python version we're using
-VER=2.2
-
-# Expressions using the above definitions
-PYVER=python$(VER)
-
-# Use these defs when compiling against installed Python
-##INST=/usr/local
-##PYC=$(INST)/lib/$(PYVER)/config
-##PYINCL=-I$(INST)/include/$(PYVER) -I$(PYC)
-##PYLIBS=$(PYC)/lib$(PYVER).a
-
-# Use these defs when compiling against built Python
-PLAT=linux
-PYINCL=-I../../Include -I../../$(PLAT)
-PYLIBS=../../$(PLAT)/lib$(PYVER).a
-
-# Libraries to link with -- very installation dependent
-# (See LIBS= in Modules/Makefile in build tree)
-RLLIBS=-lreadline -ltermcap
-OTHERLIBS=-lnsl -lpthread -ldl -lm -ldb -lutil
-
-# Compilation and link flags -- no need to change normally
-CFLAGS=$(OPT)
-CPPFLAGS=$(PYINCL)
-LIBS=$(PYLIBS) $(RLLIBS) $(OTHERLIBS)
-
-# Default port for the pysvr application
-PORT=4000
-
-# Default target
-all: pysvr
-
-# Target to build pysvr
-pysvr: pysvr.o $(PYOBJS) $(PYLIBS)
- $(LINKCC) pysvr.o $(LIBS) -o pysvr
-
-# Target to build and run pysvr
-run: pysvr
- pysvr $(PORT)
-
-# Target to clean up the directory
-clean:
- -rm -f pysvr *.o *~ core
diff --git a/Demo/pysvr/README b/Demo/pysvr/README
deleted file mode 100644
index 5e64e38bb4..0000000000
--- a/Demo/pysvr/README
+++ /dev/null
@@ -1,9 +0,0 @@
-This is an example of a multi-threaded C application embedding a
-Python interpreter.
-
-The particular application is a multi-threaded telnet-like server that
-provides you with a Python prompt (instead of a shell prompt).
-
-The file pysvr.py is a prototype in Python.
-
-THIS APPLICATION IS NOT SECURE -- ONLY USE IT FOR TESTING!
diff --git a/Demo/pysvr/pysvr.c b/Demo/pysvr/pysvr.c
deleted file mode 100644
index cced6da4bf..0000000000
--- a/Demo/pysvr/pysvr.c
+++ /dev/null
@@ -1,370 +0,0 @@
-/* A multi-threaded telnet-like server that gives a Python prompt.
-
-Usage: pysvr [port]
-
-For security reasons, it only accepts requests from the current host.
-This can still be insecure, but restricts violations from people who
-can log in on your machine. Use with caution!
-
-*/
-
-#include
-#include
-#include
-#include
-#include
-
-#include
-#include
-#include
-
-#include
-#include
-
-/* XXX Umpfh.
- Python.h defines a typedef destructor, which conflicts with pthread.h.
- So Python.h must be included after pthread.h. */
-
-#include "Python.h"
-
-extern int Py_VerboseFlag;
-
-#ifndef PORT
-#define PORT 4000
-#endif
-
-struct workorder {
- int conn;
- struct sockaddr_in addr;
-};
-
-/* Forward */
-static void init_python(void);
-static void usage(void);
-static void oprogname(void);
-static void main_thread(int);
-static void create_thread(int, struct sockaddr_in *);
-static void *service_thread(struct workorder *);
-static void run_interpreter(FILE *, FILE *);
-static int run_command(char *, PyObject *);
-static void ps(void);
-
-static char *progname = "pysvr";
-
-static PyThreadState *gtstate;
-
-main(int argc, char **argv)
-{
- int port = PORT;
- int c;
-
- if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0')
- progname = argv[0];
-
- while ((c = getopt(argc, argv, "v")) != EOF) {
- switch (c) {
- case 'v':
- Py_VerboseFlag++;
- break;
- default:
- usage();
- }
- }
-
- if (optind < argc) {
- if (optind+1 < argc) {
- oprogname();
- fprintf(stderr, "too many arguments\n");
- usage();
- }
- port = atoi(argv[optind]);
- if (port <= 0) {
- fprintf(stderr, "bad port (%s)\n", argv[optind]);
- usage();
- }
- }
-
- main_thread(port);
-
- fprintf(stderr, "Bye.\n");
-
- exit(0);
-}
-
-static char usage_line[] = "usage: %s [port]\n";
-
-static void
-usage(void)
-{
- fprintf(stderr, usage_line, progname);
- exit(2);
-}
-
-static void
-main_thread(int port)
-{
- int sock, conn, size, i;
- struct sockaddr_in addr, clientaddr;
-
- sock = socket(PF_INET, SOCK_STREAM, 0);
- if (sock < 0) {
- oprogname();
- perror("can't create socket");
- exit(1);
- }
-
-#ifdef SO_REUSEADDR
- i = 1;
- setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i);
-#endif
-
- memset((char *)&addr, '\0', sizeof addr);
- addr.sin_family = AF_INET;
- addr.sin_port = htons(port);
- addr.sin_addr.s_addr = 0L;
- if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) {
- oprogname();
- perror("can't bind socket to address");
- exit(1);
- }
-
- if (listen(sock, 5) < 0) {
- oprogname();
- perror("can't listen on socket");
- exit(1);
- }
-
- fprintf(stderr, "Listening on port %d...\n", port);
-
- for (i = 0; ; i++) {
- size = sizeof clientaddr;
- memset((char *) &clientaddr, '\0', size);
- conn = accept(sock, (struct sockaddr *) &clientaddr, &size);
- if (conn < 0) {
- oprogname();
- perror("can't accept connection from socket");
- exit(1);
- }
-
- size = sizeof addr;
- memset((char *) &addr, '\0', size);
- if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) {
- oprogname();
- perror("can't get socket name of connection");
- exit(1);
- }
- if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) {
- oprogname();
- perror("connection from non-local host refused");
- fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n",
- ntohl(addr.sin_addr.s_addr),
- ntohl(clientaddr.sin_addr.s_addr));
- close(conn);
- continue;
- }
- if (i == 4) {
- close(conn);
- break;
- }
- create_thread(conn, &clientaddr);
- }
-
- close(sock);
-
- if (gtstate) {
- PyEval_AcquireThread(gtstate);
- gtstate = NULL;
- Py_Finalize();
- /* And a second time, just because we can. */
- Py_Finalize(); /* This should be harmless. */
- }
- exit(0);
-}
-
-static void
-create_thread(int conn, struct sockaddr_in *addr)
-{
- struct workorder *work;
- pthread_t tdata;
-
- work = malloc(sizeof(struct workorder));
- if (work == NULL) {
- oprogname();
- fprintf(stderr, "out of memory for thread.\n");
- close(conn);
- return;
- }
- work->conn = conn;
- work->addr = *addr;
-
- init_python();
-
- if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) {
- oprogname();
- perror("can't create new thread");
- close(conn);
- return;
- }
-
- if (pthread_detach(tdata) < 0) {
- oprogname();
- perror("can't detach from thread");
- }
-}
-
-static PyThreadState *the_tstate;
-static PyInterpreterState *the_interp;
-static PyObject *the_builtins;
-
-static void
-init_python(void)
-{
- if (gtstate)
- return;
- Py_Initialize(); /* Initialize the interpreter */
- PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */
- gtstate = PyEval_SaveThread(); /* Release the thread state */
-}
-
-static void *
-service_thread(struct workorder *work)
-{
- FILE *input, *output;
-
- fprintf(stderr, "Start thread for connection %d.\n", work->conn);
-
- ps();
-
- input = fdopen(work->conn, "r");
- if (input == NULL) {
- oprogname();
- perror("can't create input stream");
- goto done;
- }
-
- output = fdopen(work->conn, "w");
- if (output == NULL) {
- oprogname();
- perror("can't create output stream");
- fclose(input);
- goto done;
- }
-
- setvbuf(input, NULL, _IONBF, 0);
- setvbuf(output, NULL, _IONBF, 0);
-
- run_interpreter(input, output);
-
- fclose(input);
- fclose(output);
-
- done:
- fprintf(stderr, "End thread for connection %d.\n", work->conn);
- close(work->conn);
- free(work);
-}
-
-static void
-oprogname(void)
-{
- int save = errno;
- fprintf(stderr, "%s: ", progname);
- errno = save;
-}
-
-static void
-run_interpreter(FILE *input, FILE *output)
-{
- PyThreadState *tstate;
- PyObject *new_stdin, *new_stdout;
- PyObject *mainmod, *globals;
- char buffer[1000];
- char *p, *q;
- int n, end;
-
- PyEval_AcquireLock();
- tstate = Py_NewInterpreter();
- if (tstate == NULL) {
- fprintf(output, "Sorry -- can't create an interpreter\n");
- return;
- }
-
- mainmod = PyImport_AddModule("__main__");
- globals = PyModule_GetDict(mainmod);
- Py_INCREF(globals);
-
- new_stdin = PyFile_FromFile(input, "", "r", NULL);
- new_stdout = PyFile_FromFile(output, "", "w", NULL);
-
- PySys_SetObject("stdin", new_stdin);
- PySys_SetObject("stdout", new_stdout);
- PySys_SetObject("stderr", new_stdout);
-
- for (n = 1; !PyErr_Occurred(); n++) {
- Py_BEGIN_ALLOW_THREADS
- fprintf(output, "%d> ", n);
- p = fgets(buffer, sizeof buffer, input);
- Py_END_ALLOW_THREADS
-
- if (p == NULL)
- break;
- if (p[0] == '\377' && p[1] == '\354')
- break;
-
- q = strrchr(p, '\r');
- if (q && q[1] == '\n' && q[2] == '\0') {
- *q++ = '\n';
- *q++ = '\0';
- }
-
- while (*p && isspace(*p))
- p++;
- if (p[0] == '#' || p[0] == '\0')
- continue;
-
- end = run_command(buffer, globals);
- if (end < 0)
- PyErr_Print();
-
- if (end)
- break;
- }
-
- Py_XDECREF(globals);
- Py_XDECREF(new_stdin);
- Py_XDECREF(new_stdout);
-
- Py_EndInterpreter(tstate);
- PyEval_ReleaseLock();
-
- fprintf(output, "Goodbye!\n");
-}
-
-static int
-run_command(char *buffer, PyObject *globals)
-{
- PyObject *m, *d, *v;
- fprintf(stderr, "run_command: %s", buffer);
- if (strchr(buffer, '\n') == NULL)
- fprintf(stderr, "\n");
- v = PyRun_String(buffer, Py_single_input, globals, globals);
- if (v == NULL) {
- if (PyErr_Occurred() == PyExc_SystemExit) {
- PyErr_Clear();
- return 1;
- }
- PyErr_Print();
- return 0;
- }
- Py_DECREF(v);
- return 0;
-}
-
-static void
-ps(void)
-{
- char buffer[100];
- PyOS_snprintf(buffer, sizeof(buffer),
- "ps -l -p %d 1:
- raise getopt.error, "Too many arguments."
- except getopt.error, msg:
- usage(msg)
- for o, a in opts:
- pass
- if args:
- try:
- port = string.atoi(args[0])
- except ValueError, msg:
- usage(msg)
- else:
- port = PORT
- main_thread(port)
-
-def usage(msg=None):
- sys.stdout = sys.stderr
- if msg:
- print msg
- print "\n", __doc__,
- sys.exit(2)
-
-def main_thread(port):
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.bind(("", port))
- sock.listen(5)
- print "Listening on port", port, "..."
- while 1:
- (conn, addr) = sock.accept()
- if addr[0] != conn.getsockname()[0]:
- conn.close()
- print "Refusing connection from non-local host", addr[0], "."
- continue
- thread.start_new_thread(service_thread, (conn, addr))
- del conn, addr
-
-def service_thread(conn, addr):
- (caddr, cport) = addr
- print "Thread %s has connection from %s.\n" % (str(thread.get_ident()),
- caddr),
- stdin = conn.makefile("r")
- stdout = conn.makefile("w", 0)
- run_interpreter(stdin, stdout)
- print "Thread %s is done.\n" % str(thread.get_ident()),
-
-def run_interpreter(stdin, stdout):
- globals = {}
- try:
- str(sys.ps1)
- except:
- sys.ps1 = ">>> "
- source = ""
- while 1:
- stdout.write(sys.ps1)
- line = stdin.readline()
- if line[:2] == '\377\354':
- line = ""
- if not line and not source:
- break
- if line[-2:] == '\r\n':
- line = line[:-2] + '\n'
- source = source + line
- try:
- code = compile_command(source)
- except SyntaxError, err:
- source = ""
- traceback.print_exception(SyntaxError, err, None, file=stdout)
- continue
- if not code:
- continue
- source = ""
- try:
- run_command(code, stdin, stdout, globals)
- except SystemExit, how:
- if how:
- try:
- how = str(how)
- except:
- how = ""
- stdout.write("Exit %s\n" % how)
- break
- stdout.write("\nGoodbye.\n")
-
-def run_command(code, stdin, stdout, globals):
- save = sys.stdin, sys.stdout, sys.stderr
- try:
- sys.stdout = sys.stderr = stdout
- sys.stdin = stdin
- try:
- exec code in globals
- except SystemExit, how:
- raise SystemExit, how, sys.exc_info()[2]
- except:
- type, value, tb = sys.exc_info()
- if tb: tb = tb.tb_next
- traceback.print_exception(type, value, tb)
- del tb
- finally:
- sys.stdin, sys.stdout, sys.stderr = save
-
-from code import compile_command
-
-main()
diff --git a/Demo/rpc/MANIFEST b/Demo/rpc/MANIFEST
deleted file mode 100644
index e65f3ebee8..0000000000
--- a/Demo/rpc/MANIFEST
+++ /dev/null
@@ -1,10 +0,0 @@
- File Name Archive # Description
------------------------------------------------------------
- MANIFEST 1 This shipping list
- README 1
- T.py 1
- mountclient.py 1
- nfsclient.py 1
- rpc.py 1
- test 1
- xdr.py 1
diff --git a/Demo/rpc/README b/Demo/rpc/README
deleted file mode 100644
index 97948a3384..0000000000
--- a/Demo/rpc/README
+++ /dev/null
@@ -1,31 +0,0 @@
-This is a Python interface to Sun RPC, designed and implemented mostly
-by reading the Internet RFCs about the subject.
-
-*** NOTE: xdr.py has evolved into the standard module xdrlib.py ***
-
-There are two library modules, xdr.py and rpc.py, and several example
-clients: mountclient.py, nfsclient.py, and rnusersclient.py,
-implementing the NFS Mount protocol, (part of) the NFS protocol, and
-the "rnusers" protocol (used by rusers(1)), respectively. The latter
-demonstrates the use of broadcast via the Port mapper's CALLIT
-procedure.
-
-There is also a way to create servers in Python.
-
-To test the nfs client, run it from the shell with something like this:
-
- python -c 'import nfsclient; nfsclient.test()' [hostname [filesystemname]]
-
-When called without a filesystemname, it lists the filesystems at the
-host; default host is the local machine.
-
-Other clients are tested similarly.
-
-For hostname, use e.g. wuarchive.wustl.edu or gatekeeper.dec.com (two
-hosts that are known to export NFS filesystems with little restrictions).
-
-There are now two different RPC compilers:
-
-1) Wim Lewis rpcgen.py found on http://www.omnigroup.com/~wiml/soft/stale-index.html#python.
-
-2) Peter Åstrands rpcgen.py, which is part of "pynfs" (http://www.cendio.se/~peter/pynfs/).
diff --git a/Demo/rpc/T.py b/Demo/rpc/T.py
deleted file mode 100644
index abf3a06d05..0000000000
--- a/Demo/rpc/T.py
+++ /dev/null
@@ -1,22 +0,0 @@
-# Simple interface to report execution times of program fragments.
-# Call TSTART() to reset the timer, TSTOP(...) to report times.
-
-import sys, os, time
-
-def TSTART():
- global t0, t1
- u, s, cu, cs = os.times()
- t0 = u+cu, s+cs, time.time()
-
-def TSTOP(*label):
- global t0, t1
- u, s, cu, cs = os.times()
- t1 = u+cu, s+cs, time.time()
- tt = []
- for i in range(3):
- tt.append(t1[i] - t0[i])
- [u, s, r] = tt
- msg = ''
- for x in label: msg = msg + (x + ' ')
- msg = msg + `u` + ' user, ' + `s` + ' sys, ' + `r` + ' real\n'
- sys.stderr.write(msg)
diff --git a/Demo/rpc/mountclient.py b/Demo/rpc/mountclient.py
deleted file mode 100644
index 8a4b1b64d8..0000000000
--- a/Demo/rpc/mountclient.py
+++ /dev/null
@@ -1,202 +0,0 @@
-# Mount RPC client -- RFC 1094 (NFS), Appendix A
-
-# This module demonstrates how to write your own RPC client in Python.
-# When this example was written, there was no RPC compiler for
-# Python. Without such a compiler, you must first create classes
-# derived from Packer and Unpacker to handle the data types for the
-# server you want to interface to. You then write the client class.
-# If you want to support both the TCP and the UDP version of a
-# protocol, use multiple inheritance as shown below.
-
-
-import rpc
-from rpc import Packer, Unpacker, TCPClient, UDPClient
-
-
-# Program number and version for the mount protocol
-MOUNTPROG = 100005
-MOUNTVERS = 1
-
-# Size of the 'fhandle' opaque structure
-FHSIZE = 32
-
-
-# Packer derived class for Mount protocol clients.
-# The only thing we need to pack beyond basic types is an 'fhandle'
-
-class MountPacker(Packer):
-
- def pack_fhandle(self, fhandle):
- self.pack_fopaque(FHSIZE, fhandle)
-
-
-# Unpacker derived class for Mount protocol clients.
-# The important types we need to unpack are fhandle, fhstatus,
-# mountlist and exportlist; mountstruct, exportstruct and groups are
-# used to unpack components of mountlist and exportlist and the
-# corresponding functions are passed as function argument to the
-# generic unpack_list function.
-
-class MountUnpacker(Unpacker):
-
- def unpack_fhandle(self):
- return self.unpack_fopaque(FHSIZE)
-
- def unpack_fhstatus(self):
- status = self.unpack_uint()
- if status == 0:
- fh = self.unpack_fhandle()
- else:
- fh = None
- return status, fh
-
- def unpack_mountlist(self):
- return self.unpack_list(self.unpack_mountstruct)
-
- def unpack_mountstruct(self):
- hostname = self.unpack_string()
- directory = self.unpack_string()
- return (hostname, directory)
-
- def unpack_exportlist(self):
- return self.unpack_list(self.unpack_exportstruct)
-
- def unpack_exportstruct(self):
- filesys = self.unpack_string()
- groups = self.unpack_groups()
- return (filesys, groups)
-
- def unpack_groups(self):
- return self.unpack_list(self.unpack_string)
-
-
-# These are the procedures specific to the Mount client class.
-# Think of this as a derived class of either TCPClient or UDPClient.
-
-class PartialMountClient:
-
- # This method is called by Client.__init__ to initialize
- # self.packer and self.unpacker
- def addpackers(self):
- self.packer = MountPacker()
- self.unpacker = MountUnpacker('')
-
- # This method is called by Client.__init__ to bind the socket
- # to a particular network interface and port. We use the
- # default network interface, but if we're running as root,
- # we want to bind to a reserved port
- def bindsocket(self):
- import os
- try:
- uid = os.getuid()
- except AttributeError:
- uid = 1
- if uid == 0:
- port = rpc.bindresvport(self.sock, '')
- # 'port' is not used
- else:
- self.sock.bind(('', 0))
-
- # This function is called to cough up a suitable
- # authentication object for a call to procedure 'proc'.
- def mkcred(self):
- if self.cred == None:
- self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default()
- return self.cred
-
- # The methods Mnt, Dump etc. each implement one Remote
- # Procedure Call. This is done by calling self.make_call()
- # with as arguments:
- #
- # - the procedure number
- # - the arguments (or None)
- # - the "packer" function for the arguments (or None)
- # - the "unpacker" function for the return value (or None)
- #
- # The packer and unpacker function, if not None, *must* be
- # methods of self.packer and self.unpacker, respectively.
- # A value of None means that there are no arguments or is no
- # return value, respectively.
- #
- # The return value from make_call() is the return value from
- # the remote procedure call, as unpacked by the "unpacker"
- # function, or None if the unpacker function is None.
- #
- # (Even if you expect a result of None, you should still
- # return the return value from make_call(), since this may be
- # needed by a broadcasting version of the class.)
- #
- # If the call fails, make_call() raises an exception
- # (this includes time-outs and invalid results).
- #
- # Note that (at least with the UDP protocol) there is no
- # guarantee that a call is executed at most once. When you do
- # get a reply, you know it has been executed at least once;
- # when you don't get a reply, you know nothing.
-
- def Mnt(self, directory):
- return self.make_call(1, directory, \
- self.packer.pack_string, \
- self.unpacker.unpack_fhstatus)
-
- def Dump(self):
- return self.make_call(2, None, \
- None, self.unpacker.unpack_mountlist)
-
- def Umnt(self, directory):
- return self.make_call(3, directory, \
- self.packer.pack_string, None)
-
- def Umntall(self):
- return self.make_call(4, None, None, None)
-
- def Export(self):
- return self.make_call(5, None, \
- None, self.unpacker.unpack_exportlist)
-
-
-# We turn the partial Mount client into a full one for either protocol
-# by use of multiple inheritance. (In general, when class C has base
-# classes B1...Bn, if x is an instance of class C, methods of x are
-# searched first in C, then in B1, then in B2, ..., finally in Bn.)
-
-class TCPMountClient(PartialMountClient, TCPClient):
-
- def __init__(self, host):
- TCPClient.__init__(self, host, MOUNTPROG, MOUNTVERS)
-
-
-class UDPMountClient(PartialMountClient, UDPClient):
-
- def __init__(self, host):
- UDPClient.__init__(self, host, MOUNTPROG, MOUNTVERS)
-
-
-# A little test program for the Mount client. This takes a host as
-# command line argument (default the local machine), prints its export
-# list, and attempts to mount and unmount each exported files system.
-# An optional first argument of -t or -u specifies the protocol to use
-# (TCP or UDP), default is UDP.
-
-def test():
- import sys
- if sys.argv[1:] and sys.argv[1] == '-t':
- C = TCPMountClient
- del sys.argv[1]
- elif sys.argv[1:] and sys.argv[1] == '-u':
- C = UDPMountClient
- del sys.argv[1]
- else:
- C = UDPMountClient
- if sys.argv[1:]: host = sys.argv[1]
- else: host = ''
- mcl = C(host)
- list = mcl.Export()
- for item in list:
- print item
- try:
- mcl.Mnt(item[0])
- except:
- print 'Sorry'
- continue
- mcl.Umnt(item[0])
diff --git a/Demo/rpc/nfsclient.py b/Demo/rpc/nfsclient.py
deleted file mode 100644
index 37ec46c047..0000000000
--- a/Demo/rpc/nfsclient.py
+++ /dev/null
@@ -1,201 +0,0 @@
-# NFS RPC client -- RFC 1094
-
-# XXX This is not yet complete.
-# XXX Only GETATTR, SETTTR, LOOKUP and READDIR are supported.
-
-# (See mountclient.py for some hints on how to write RPC clients in
-# Python in general)
-
-import rpc
-from rpc import UDPClient, TCPClient
-from mountclient import FHSIZE, MountPacker, MountUnpacker
-
-NFS_PROGRAM = 100003
-NFS_VERSION = 2
-
-# enum stat
-NFS_OK = 0
-# (...many error values...)
-
-# enum ftype
-NFNON = 0
-NFREG = 1
-NFDIR = 2
-NFBLK = 3
-NFCHR = 4
-NFLNK = 5
-
-
-class NFSPacker(MountPacker):
-
- def pack_sattrargs(self, sa):
- file, attributes = sa
- self.pack_fhandle(file)
- self.pack_sattr(attributes)
-
- def pack_sattr(self, sa):
- mode, uid, gid, size, atime, mtime = sa
- self.pack_uint(mode)
- self.pack_uint(uid)
- self.pack_uint(gid)
- self.pack_uint(size)
- self.pack_timeval(atime)
- self.pack_timeval(mtime)
-
- def pack_diropargs(self, da):
- dir, name = da
- self.pack_fhandle(dir)
- self.pack_string(name)
-
- def pack_readdirargs(self, ra):
- dir, cookie, count = ra
- self.pack_fhandle(dir)
- self.pack_uint(cookie)
- self.pack_uint(count)
-
- def pack_timeval(self, tv):
- secs, usecs = tv
- self.pack_uint(secs)
- self.pack_uint(usecs)
-
-
-class NFSUnpacker(MountUnpacker):
-
- def unpack_readdirres(self):
- status = self.unpack_enum()
- if status == NFS_OK:
- entries = self.unpack_list(self.unpack_entry)
- eof = self.unpack_bool()
- rest = (entries, eof)
- else:
- rest = None
- return (status, rest)
-
- def unpack_entry(self):
- fileid = self.unpack_uint()
- name = self.unpack_string()
- cookie = self.unpack_uint()
- return (fileid, name, cookie)
-
- def unpack_diropres(self):
- status = self.unpack_enum()
- if status == NFS_OK:
- fh = self.unpack_fhandle()
- fa = self.unpack_fattr()
- rest = (fh, fa)
- else:
- rest = None
- return (status, rest)
-
- def unpack_attrstat(self):
- status = self.unpack_enum()
- if status == NFS_OK:
- attributes = self.unpack_fattr()
- else:
- attributes = None
- return status, attributes
-
- def unpack_fattr(self):
- type = self.unpack_enum()
- mode = self.unpack_uint()
- nlink = self.unpack_uint()
- uid = self.unpack_uint()
- gid = self.unpack_uint()
- size = self.unpack_uint()
- blocksize = self.unpack_uint()
- rdev = self.unpack_uint()
- blocks = self.unpack_uint()
- fsid = self.unpack_uint()
- fileid = self.unpack_uint()
- atime = self.unpack_timeval()
- mtime = self.unpack_timeval()
- ctime = self.unpack_timeval()
- return (type, mode, nlink, uid, gid, size, blocksize, \
- rdev, blocks, fsid, fileid, atime, mtime, ctime)
-
- def unpack_timeval(self):
- secs = self.unpack_uint()
- usecs = self.unpack_uint()
- return (secs, usecs)
-
-
-class NFSClient(UDPClient):
-
- def __init__(self, host):
- UDPClient.__init__(self, host, NFS_PROGRAM, NFS_VERSION)
-
- def addpackers(self):
- self.packer = NFSPacker()
- self.unpacker = NFSUnpacker('')
-
- def mkcred(self):
- if self.cred == None:
- self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default()
- return self.cred
-
- def Getattr(self, fh):
- return self.make_call(1, fh, \
- self.packer.pack_fhandle, \
- self.unpacker.unpack_attrstat)
-
- def Setattr(self, sa):
- return self.make_call(2, sa, \
- self.packer.pack_sattrargs, \
- self.unpacker.unpack_attrstat)
-
- # Root() is obsolete
-
- def Lookup(self, da):
- return self.make_call(4, da, \
- self.packer.pack_diropargs, \
- self.unpacker.unpack_diropres)
-
- # ...
-
- def Readdir(self, ra):
- return self.make_call(16, ra, \
- self.packer.pack_readdirargs, \
- self.unpacker.unpack_readdirres)
-
- # Shorthand to get the entire contents of a directory
- def Listdir(self, dir):
- list = []
- ra = (dir, 0, 2000)
- while 1:
- (status, rest) = self.Readdir(ra)
- if status <> NFS_OK:
- break
- entries, eof = rest
- last_cookie = None
- for fileid, name, cookie in entries:
- list.append((fileid, name))
- last_cookie = cookie
- if eof or last_cookie == None:
- break
- ra = (ra[0], last_cookie, ra[2])
- return list
-
-
-def test():
- import sys
- if sys.argv[1:]: host = sys.argv[1]
- else: host = ''
- if sys.argv[2:]: filesys = sys.argv[2]
- else: filesys = None
- from mountclient import UDPMountClient, TCPMountClient
- mcl = TCPMountClient(host)
- if filesys == None:
- list = mcl.Export()
- for item in list:
- print item
- return
- sf = mcl.Mnt(filesys)
- print sf
- fh = sf[1]
- if fh:
- ncl = NFSClient(host)
- as = ncl.Getattr(fh)
- print as
- list = ncl.Listdir(fh)
- for item in list: print item
- mcl.Umnt(filesys)
diff --git a/Demo/rpc/rnusersclient.py b/Demo/rpc/rnusersclient.py
deleted file mode 100644
index e9cad620fd..0000000000
--- a/Demo/rpc/rnusersclient.py
+++ /dev/null
@@ -1,98 +0,0 @@
-# Remote nusers client interface
-
-import rpc
-from rpc import Packer, Unpacker, UDPClient, BroadcastUDPClient
-
-
-class RnusersPacker(Packer):
- def pack_utmp(self, ui):
- ut_line, ut_name, ut_host, ut_time = utmp
- self.pack_string(ut_line)
- self.pack_string(ut_name)
- self.pack_string(ut_host)
- self.pack_int(ut_time)
- def pack_utmpidle(self, ui):
- ui_itmp, ui_idle = ui
- self.pack_utmp(ui_utmp)
- self.pack_uint(ui_idle)
- def pack_utmpidlearr(self, list):
- self.pack_array(list, self.pack_itmpidle)
-
-
-class RnusersUnpacker(Unpacker):
- def unpack_utmp(self):
- ut_line = self.unpack_string()
- ut_name = self.unpack_string()
- ut_host = self.unpack_string()
- ut_time = self.unpack_int()
- return ut_line, ut_name, ut_host, ut_time
- def unpack_utmpidle(self):
- ui_utmp = self.unpack_utmp()
- ui_idle = self.unpack_uint()
- return ui_utmp, ui_idle
- def unpack_utmpidlearr(self):
- return self.unpack_array(self.unpack_utmpidle)
-
-
-class PartialRnusersClient:
-
- def addpackers(self):
- self.packer = RnusersPacker()
- self.unpacker = RnusersUnpacker('')
-
- def Num(self):
- return self.make_call(1, None, None, self.unpacker.unpack_int)
-
- def Names(self):
- return self.make_call(2, None, \
- None, self.unpacker.unpack_utmpidlearr)
-
- def Allnames(self):
- return self.make_call(3, None, \
- None, self.unpacker.unpack_utmpidlearr)
-
-
-class RnusersClient(PartialRnusersClient, UDPClient):
-
- def __init__(self, host):
- UDPClient.__init__(self, host, 100002, 2)
-
-
-class BroadcastRnusersClient(PartialRnusersClient, BroadcastUDPClient):
-
- def __init__(self, bcastaddr):
- BroadcastUDPClient.__init__(self, bcastaddr, 100002, 2)
-
-
-def test():
- import sys
- if not sys.argv[1:]:
- testbcast()
- return
- else:
- host = sys.argv[1]
- c = RnusersClient(host)
- list = c.Names()
- for (line, name, host, time), idle in list:
- line = strip0(line)
- name = strip0(name)
- host = strip0(host)
- print `name`, `host`, `line`, time, idle
-
-def testbcast():
- c = BroadcastRnusersClient('')
- def listit(list, fromaddr):
- host, port = fromaddr
- print host + '\t:',
- for (line, name, host, time), idle in list:
- print strip0(name),
- print
- c.set_reply_handler(listit)
- all = c.Names()
- print 'Total Count:', len(all)
-
-def strip0(s):
- while s and s[-1] == '\0': s = s[:-1]
- return s
-
-test()
diff --git a/Demo/rpc/rpc.py b/Demo/rpc/rpc.py
deleted file mode 100644
index f44b3e4426..0000000000
--- a/Demo/rpc/rpc.py
+++ /dev/null
@@ -1,891 +0,0 @@
-# Sun RPC version 2 -- RFC1057.
-
-# XXX There should be separate exceptions for the various reasons why
-# XXX an RPC can fail, rather than using RuntimeError for everything
-
-# XXX The UDP version of the protocol resends requests when it does
-# XXX not receive a timely reply -- use only for idempotent calls!
-
-# XXX There is no provision for call timeout on TCP connections
-
-import xdr
-import socket
-import os
-
-RPCVERSION = 2
-
-CALL = 0
-REPLY = 1
-
-AUTH_NULL = 0
-AUTH_UNIX = 1
-AUTH_SHORT = 2
-AUTH_DES = 3
-
-MSG_ACCEPTED = 0
-MSG_DENIED = 1
-
-SUCCESS = 0 # RPC executed successfully
-PROG_UNAVAIL = 1 # remote hasn't exported program
-PROG_MISMATCH = 2 # remote can't support version #
-PROC_UNAVAIL = 3 # program can't support procedure
-GARBAGE_ARGS = 4 # procedure can't decode params
-
-RPC_MISMATCH = 0 # RPC version number != 2
-AUTH_ERROR = 1 # remote can't authenticate caller
-
-AUTH_BADCRED = 1 # bad credentials (seal broken)
-AUTH_REJECTEDCRED = 2 # client must begin new session
-AUTH_BADVERF = 3 # bad verifier (seal broken)
-AUTH_REJECTEDVERF = 4 # verifier expired or replayed
-AUTH_TOOWEAK = 5 # rejected for security reasons
-
-
-class Packer(xdr.Packer):
-
- def pack_auth(self, auth):
- flavor, stuff = auth
- self.pack_enum(flavor)
- self.pack_opaque(stuff)
-
- def pack_auth_unix(self, stamp, machinename, uid, gid, gids):
- self.pack_uint(stamp)
- self.pack_string(machinename)
- self.pack_uint(uid)
- self.pack_uint(gid)
- self.pack_uint(len(gids))
- for i in gids:
- self.pack_uint(i)
-
- def pack_callheader(self, xid, prog, vers, proc, cred, verf):
- self.pack_uint(xid)
- self.pack_enum(CALL)
- self.pack_uint(RPCVERSION)
- self.pack_uint(prog)
- self.pack_uint(vers)
- self.pack_uint(proc)
- self.pack_auth(cred)
- self.pack_auth(verf)
- # Caller must add procedure-specific part of call
-
- def pack_replyheader(self, xid, verf):
- self.pack_uint(xid)
- self.pack_enum(REPLY)
- self.pack_uint(MSG_ACCEPTED)
- self.pack_auth(verf)
- self.pack_enum(SUCCESS)
- # Caller must add procedure-specific part of reply
-
-
-# Exceptions
-BadRPCFormat = 'rpc.BadRPCFormat'
-BadRPCVersion = 'rpc.BadRPCVersion'
-GarbageArgs = 'rpc.GarbageArgs'
-
-class Unpacker(xdr.Unpacker):
-
- def unpack_auth(self):
- flavor = self.unpack_enum()
- stuff = self.unpack_opaque()
- return (flavor, stuff)
-
- def unpack_callheader(self):
- xid = self.unpack_uint(xid)
- temp = self.unpack_enum()
- if temp <> CALL:
- raise BadRPCFormat, 'no CALL but ' + `temp`
- temp = self.unpack_uint()
- if temp <> RPCVERSION:
- raise BadRPCVerspion, 'bad RPC version ' + `temp`
- prog = self.unpack_uint()
- vers = self.unpack_uint()
- proc = self.unpack_uint()
- cred = self.unpack_auth()
- verf = self.unpack_auth()
- return xid, prog, vers, proc, cred, verf
- # Caller must add procedure-specific part of call
-
- def unpack_replyheader(self):
- xid = self.unpack_uint()
- mtype = self.unpack_enum()
- if mtype <> REPLY:
- raise RuntimeError, 'no REPLY but ' + `mtype`
- stat = self.unpack_enum()
- if stat == MSG_DENIED:
- stat = self.unpack_enum()
- if stat == RPC_MISMATCH:
- low = self.unpack_uint()
- high = self.unpack_uint()
- raise RuntimeError, \
- 'MSG_DENIED: RPC_MISMATCH: ' + `low, high`
- if stat == AUTH_ERROR:
- stat = self.unpack_uint()
- raise RuntimeError, \
- 'MSG_DENIED: AUTH_ERROR: ' + `stat`
- raise RuntimeError, 'MSG_DENIED: ' + `stat`
- if stat <> MSG_ACCEPTED:
- raise RuntimeError, \
- 'Neither MSG_DENIED nor MSG_ACCEPTED: ' + `stat`
- verf = self.unpack_auth()
- stat = self.unpack_enum()
- if stat == PROG_UNAVAIL:
- raise RuntimeError, 'call failed: PROG_UNAVAIL'
- if stat == PROG_MISMATCH:
- low = self.unpack_uint()
- high = self.unpack_uint()
- raise RuntimeError, \
- 'call failed: PROG_MISMATCH: ' + `low, high`
- if stat == PROC_UNAVAIL:
- raise RuntimeError, 'call failed: PROC_UNAVAIL'
- if stat == GARBAGE_ARGS:
- raise RuntimeError, 'call failed: GARBAGE_ARGS'
- if stat <> SUCCESS:
- raise RuntimeError, 'call failed: ' + `stat`
- return xid, verf
- # Caller must get procedure-specific part of reply
-
-
-# Subroutines to create opaque authentication objects
-
-def make_auth_null():
- return ''
-
-def make_auth_unix(seed, host, uid, gid, groups):
- p = Packer()
- p.pack_auth_unix(seed, host, uid, gid, groups)
- return p.get_buf()
-
-def make_auth_unix_default():
- try:
- from os import getuid, getgid
- uid = getuid()
- gid = getgid()
- except ImportError:
- uid = gid = 0
- import time
- return make_auth_unix(int(time.time()-unix_epoch()), \
- socket.gethostname(), uid, gid, [])
-
-_unix_epoch = -1
-def unix_epoch():
- """Very painful calculation of when the Unix Epoch is.
-
- This is defined as the return value of time.time() on Jan 1st,
- 1970, 00:00:00 GMT.
-
- On a Unix system, this should always return 0.0. On a Mac, the
- calculations are needed -- and hard because of integer overflow
- and other limitations.
-
- """
- global _unix_epoch
- if _unix_epoch >= 0: return _unix_epoch
- import time
- now = time.time()
- localt = time.localtime(now) # (y, m, d, hh, mm, ss, ..., ..., ...)
- gmt = time.gmtime(now)
- offset = time.mktime(localt) - time.mktime(gmt)
- y, m, d, hh, mm, ss = 1970, 1, 1, 0, 0, 0
- offset, ss = divmod(ss + offset, 60)
- offset, mm = divmod(mm + offset, 60)
- offset, hh = divmod(hh + offset, 24)
- d = d + offset
- _unix_epoch = time.mktime((y, m, d, hh, mm, ss, 0, 0, 0))
- print "Unix epoch:", time.ctime(_unix_epoch)
- return _unix_epoch
-
-
-# Common base class for clients
-
-class Client:
-
- def __init__(self, host, prog, vers, port):
- self.host = host
- self.prog = prog
- self.vers = vers
- self.port = port
- self.makesocket() # Assigns to self.sock
- self.bindsocket()
- self.connsocket()
- self.lastxid = 0 # XXX should be more random?
- self.addpackers()
- self.cred = None
- self.verf = None
-
- def close(self):
- self.sock.close()
-
- def makesocket(self):
- # This MUST be overridden
- raise RuntimeError, 'makesocket not defined'
-
- def connsocket(self):
- # Override this if you don't want/need a connection
- self.sock.connect((self.host, self.port))
-
- def bindsocket(self):
- # Override this to bind to a different port (e.g. reserved)
- self.sock.bind(('', 0))
-
- def addpackers(self):
- # Override this to use derived classes from Packer/Unpacker
- self.packer = Packer()
- self.unpacker = Unpacker('')
-
- def make_call(self, proc, args, pack_func, unpack_func):
- # Don't normally override this (but see Broadcast)
- if pack_func is None and args is not None:
- raise TypeError, 'non-null args with null pack_func'
- self.start_call(proc)
- if pack_func:
- pack_func(args)
- self.do_call()
- if unpack_func:
- result = unpack_func()
- else:
- result = None
- self.unpacker.done()
- return result
-
- def start_call(self, proc):
- # Don't override this
- self.lastxid = xid = self.lastxid + 1
- cred = self.mkcred()
- verf = self.mkverf()
- p = self.packer
- p.reset()
- p.pack_callheader(xid, self.prog, self.vers, proc, cred, verf)
-
- def do_call(self):
- # This MUST be overridden
- raise RuntimeError, 'do_call not defined'
-
- def mkcred(self):
- # Override this to use more powerful credentials
- if self.cred == None:
- self.cred = (AUTH_NULL, make_auth_null())
- return self.cred
-
- def mkverf(self):
- # Override this to use a more powerful verifier
- if self.verf == None:
- self.verf = (AUTH_NULL, make_auth_null())
- return self.verf
-
- def call_0(self): # Procedure 0 is always like this
- return self.make_call(0, None, None, None)
-
-
-# Record-Marking standard support
-
-def sendfrag(sock, last, frag):
- x = len(frag)
- if last: x = x | 0x80000000L
- header = (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \
- chr(int(x>>8 & 0xff)) + chr(int(x & 0xff)))
- sock.send(header + frag)
-
-def sendrecord(sock, record):
- sendfrag(sock, 1, record)
-
-def recvfrag(sock):
- header = sock.recv(4)
- if len(header) < 4:
- raise EOFError
- x = long(ord(header[0]))<<24 | ord(header[1])<<16 | \
- ord(header[2])<<8 | ord(header[3])
- last = ((x & 0x80000000) != 0)
- n = int(x & 0x7fffffff)
- frag = ''
- while n > 0:
- buf = sock.recv(n)
- if not buf: raise EOFError
- n = n - len(buf)
- frag = frag + buf
- return last, frag
-
-def recvrecord(sock):
- record = ''
- last = 0
- while not last:
- last, frag = recvfrag(sock)
- record = record + frag
- return record
-
-
-# Try to bind to a reserved port (must be root)
-
-last_resv_port_tried = None
-def bindresvport(sock, host):
- global last_resv_port_tried
- FIRST, LAST = 600, 1024 # Range of ports to try
- if last_resv_port_tried == None:
- import os
- last_resv_port_tried = FIRST + os.getpid() % (LAST-FIRST)
- for i in range(last_resv_port_tried, LAST) + \
- range(FIRST, last_resv_port_tried):
- last_resv_port_tried = i
- try:
- sock.bind((host, i))
- return last_resv_port_tried
- except socket.error, (errno, msg):
- if errno <> 114:
- raise socket.error, (errno, msg)
- raise RuntimeError, 'can\'t assign reserved port'
-
-
-# Client using TCP to a specific port
-
-class RawTCPClient(Client):
-
- def makesocket(self):
- self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-
- def do_call(self):
- call = self.packer.get_buf()
- sendrecord(self.sock, call)
- reply = recvrecord(self.sock)
- u = self.unpacker
- u.reset(reply)
- xid, verf = u.unpack_replyheader()
- if xid <> self.lastxid:
- # Can't really happen since this is TCP...
- raise RuntimeError, 'wrong xid in reply ' + `xid` + \
- ' instead of ' + `self.lastxid`
-
-
-# Client using UDP to a specific port
-
-class RawUDPClient(Client):
-
- def makesocket(self):
- self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-
- def do_call(self):
- call = self.packer.get_buf()
- self.sock.send(call)
- try:
- from select import select
- except ImportError:
- print 'WARNING: select not found, RPC may hang'
- select = None
- BUFSIZE = 8192 # Max UDP buffer size
- timeout = 1
- count = 5
- while 1:
- r, w, x = [self.sock], [], []
- if select:
- r, w, x = select(r, w, x, timeout)
- if self.sock not in r:
- count = count - 1
- if count < 0: raise RuntimeError, 'timeout'
- if timeout < 25: timeout = timeout *2
-## print 'RESEND', timeout, count
- self.sock.send(call)
- continue
- reply = self.sock.recv(BUFSIZE)
- u = self.unpacker
- u.reset(reply)
- xid, verf = u.unpack_replyheader()
- if xid <> self.lastxid:
-## print 'BAD xid'
- continue
- break
-
-
-# Client using UDP broadcast to a specific port
-
-class RawBroadcastUDPClient(RawUDPClient):
-
- def __init__(self, bcastaddr, prog, vers, port):
- RawUDPClient.__init__(self, bcastaddr, prog, vers, port)
- self.reply_handler = None
- self.timeout = 30
-
- def connsocket(self):
- # Don't connect -- use sendto
- self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
-
- def set_reply_handler(self, reply_handler):
- self.reply_handler = reply_handler
-
- def set_timeout(self, timeout):
- self.timeout = timeout # Use None for infinite timeout
-
- def make_call(self, proc, args, pack_func, unpack_func):
- if pack_func is None and args is not None:
- raise TypeError, 'non-null args with null pack_func'
- self.start_call(proc)
- if pack_func:
- pack_func(args)
- call = self.packer.get_buf()
- self.sock.sendto(call, (self.host, self.port))
- try:
- from select import select
- except ImportError:
- print 'WARNING: select not found, broadcast will hang'
- select = None
- BUFSIZE = 8192 # Max UDP buffer size (for reply)
- replies = []
- if unpack_func is None:
- def dummy(): pass
- unpack_func = dummy
- while 1:
- r, w, x = [self.sock], [], []
- if select:
- if self.timeout is None:
- r, w, x = select(r, w, x)
- else:
- r, w, x = select(r, w, x, self.timeout)
- if self.sock not in r:
- break
- reply, fromaddr = self.sock.recvfrom(BUFSIZE)
- u = self.unpacker
- u.reset(reply)
- xid, verf = u.unpack_replyheader()
- if xid <> self.lastxid:
-## print 'BAD xid'
- continue
- reply = unpack_func()
- self.unpacker.done()
- replies.append((reply, fromaddr))
- if self.reply_handler:
- self.reply_handler(reply, fromaddr)
- return replies
-
-
-# Port mapper interface
-
-# Program number, version and (fixed!) port number
-PMAP_PROG = 100000
-PMAP_VERS = 2
-PMAP_PORT = 111
-
-# Procedure numbers
-PMAPPROC_NULL = 0 # (void) -> void
-PMAPPROC_SET = 1 # (mapping) -> bool
-PMAPPROC_UNSET = 2 # (mapping) -> bool
-PMAPPROC_GETPORT = 3 # (mapping) -> unsigned int
-PMAPPROC_DUMP = 4 # (void) -> pmaplist
-PMAPPROC_CALLIT = 5 # (call_args) -> call_result
-
-# A mapping is (prog, vers, prot, port) and prot is one of:
-
-IPPROTO_TCP = 6
-IPPROTO_UDP = 17
-
-# A pmaplist is a variable-length list of mappings, as follows:
-# either (1, mapping, pmaplist) or (0).
-
-# A call_args is (prog, vers, proc, args) where args is opaque;
-# a call_result is (port, res) where res is opaque.
-
-
-class PortMapperPacker(Packer):
-
- def pack_mapping(self, mapping):
- prog, vers, prot, port = mapping
- self.pack_uint(prog)
- self.pack_uint(vers)
- self.pack_uint(prot)
- self.pack_uint(port)
-
- def pack_pmaplist(self, list):
- self.pack_list(list, self.pack_mapping)
-
- def pack_call_args(self, ca):
- prog, vers, proc, args = ca
- self.pack_uint(prog)
- self.pack_uint(vers)
- self.pack_uint(proc)
- self.pack_opaque(args)
-
-
-class PortMapperUnpacker(Unpacker):
-
- def unpack_mapping(self):
- prog = self.unpack_uint()
- vers = self.unpack_uint()
- prot = self.unpack_uint()
- port = self.unpack_uint()
- return prog, vers, prot, port
-
- def unpack_pmaplist(self):
- return self.unpack_list(self.unpack_mapping)
-
- def unpack_call_result(self):
- port = self.unpack_uint()
- res = self.unpack_opaque()
- return port, res
-
-
-class PartialPortMapperClient:
-
- def addpackers(self):
- self.packer = PortMapperPacker()
- self.unpacker = PortMapperUnpacker('')
-
- def Set(self, mapping):
- return self.make_call(PMAPPROC_SET, mapping, \
- self.packer.pack_mapping, \
- self.unpacker.unpack_uint)
-
- def Unset(self, mapping):
- return self.make_call(PMAPPROC_UNSET, mapping, \
- self.packer.pack_mapping, \
- self.unpacker.unpack_uint)
-
- def Getport(self, mapping):
- return self.make_call(PMAPPROC_GETPORT, mapping, \
- self.packer.pack_mapping, \
- self.unpacker.unpack_uint)
-
- def Dump(self):
- return self.make_call(PMAPPROC_DUMP, None, \
- None, \
- self.unpacker.unpack_pmaplist)
-
- def Callit(self, ca):
- return self.make_call(PMAPPROC_CALLIT, ca, \
- self.packer.pack_call_args, \
- self.unpacker.unpack_call_result)
-
-
-class TCPPortMapperClient(PartialPortMapperClient, RawTCPClient):
-
- def __init__(self, host):
- RawTCPClient.__init__(self, \
- host, PMAP_PROG, PMAP_VERS, PMAP_PORT)
-
-
-class UDPPortMapperClient(PartialPortMapperClient, RawUDPClient):
-
- def __init__(self, host):
- RawUDPClient.__init__(self, \
- host, PMAP_PROG, PMAP_VERS, PMAP_PORT)
-
-
-class BroadcastUDPPortMapperClient(PartialPortMapperClient, \
- RawBroadcastUDPClient):
-
- def __init__(self, bcastaddr):
- RawBroadcastUDPClient.__init__(self, \
- bcastaddr, PMAP_PROG, PMAP_VERS, PMAP_PORT)
-
-
-# Generic clients that find their server through the Port mapper
-
-class TCPClient(RawTCPClient):
-
- def __init__(self, host, prog, vers):
- pmap = TCPPortMapperClient(host)
- port = pmap.Getport((prog, vers, IPPROTO_TCP, 0))
- pmap.close()
- if port == 0:
- raise RuntimeError, 'program not registered'
- RawTCPClient.__init__(self, host, prog, vers, port)
-
-
-class UDPClient(RawUDPClient):
-
- def __init__(self, host, prog, vers):
- pmap = UDPPortMapperClient(host)
- port = pmap.Getport((prog, vers, IPPROTO_UDP, 0))
- pmap.close()
- if port == 0:
- raise RuntimeError, 'program not registered'
- RawUDPClient.__init__(self, host, prog, vers, port)
-
-
-class BroadcastUDPClient(Client):
-
- def __init__(self, bcastaddr, prog, vers):
- self.pmap = BroadcastUDPPortMapperClient(bcastaddr)
- self.pmap.set_reply_handler(self.my_reply_handler)
- self.prog = prog
- self.vers = vers
- self.user_reply_handler = None
- self.addpackers()
-
- def close(self):
- self.pmap.close()
-
- def set_reply_handler(self, reply_handler):
- self.user_reply_handler = reply_handler
-
- def set_timeout(self, timeout):
- self.pmap.set_timeout(timeout)
-
- def my_reply_handler(self, reply, fromaddr):
- port, res = reply
- self.unpacker.reset(res)
- result = self.unpack_func()
- self.unpacker.done()
- self.replies.append((result, fromaddr))
- if self.user_reply_handler is not None:
- self.user_reply_handler(result, fromaddr)
-
- def make_call(self, proc, args, pack_func, unpack_func):
- self.packer.reset()
- if pack_func:
- pack_func(args)
- if unpack_func is None:
- def dummy(): pass
- self.unpack_func = dummy
- else:
- self.unpack_func = unpack_func
- self.replies = []
- packed_args = self.packer.get_buf()
- dummy_replies = self.pmap.Callit( \
- (self.prog, self.vers, proc, packed_args))
- return self.replies
-
-
-# Server classes
-
-# These are not symmetric to the Client classes
-# XXX No attempt is made to provide authorization hooks yet
-
-class Server:
-
- def __init__(self, host, prog, vers, port):
- self.host = host # Should normally be '' for default interface
- self.prog = prog
- self.vers = vers
- self.port = port # Should normally be 0 for random port
- self.makesocket() # Assigns to self.sock and self.prot
- self.bindsocket()
- self.host, self.port = self.sock.getsockname()
- self.addpackers()
-
- def register(self):
- mapping = self.prog, self.vers, self.prot, self.port
- p = TCPPortMapperClient(self.host)
- if not p.Set(mapping):
- raise RuntimeError, 'register failed'
-
- def unregister(self):
- mapping = self.prog, self.vers, self.prot, self.port
- p = TCPPortMapperClient(self.host)
- if not p.Unset(mapping):
- raise RuntimeError, 'unregister failed'
-
- def handle(self, call):
- # Don't use unpack_header but parse the header piecewise
- # XXX I have no idea if I am using the right error responses!
- self.unpacker.reset(call)
- self.packer.reset()
- xid = self.unpacker.unpack_uint()
- self.packer.pack_uint(xid)
- temp = self.unpacker.unpack_enum()
- if temp <> CALL:
- return None # Not worthy of a reply
- self.packer.pack_uint(REPLY)
- temp = self.unpacker.unpack_uint()
- if temp <> RPCVERSION:
- self.packer.pack_uint(MSG_DENIED)
- self.packer.pack_uint(RPC_MISMATCH)
- self.packer.pack_uint(RPCVERSION)
- self.packer.pack_uint(RPCVERSION)
- return self.packer.get_buf()
- self.packer.pack_uint(MSG_ACCEPTED)
- self.packer.pack_auth((AUTH_NULL, make_auth_null()))
- prog = self.unpacker.unpack_uint()
- if prog <> self.prog:
- self.packer.pack_uint(PROG_UNAVAIL)
- return self.packer.get_buf()
- vers = self.unpacker.unpack_uint()
- if vers <> self.vers:
- self.packer.pack_uint(PROG_MISMATCH)
- self.packer.pack_uint(self.vers)
- self.packer.pack_uint(self.vers)
- return self.packer.get_buf()
- proc = self.unpacker.unpack_uint()
- methname = 'handle_' + `proc`
- try:
- meth = getattr(self, methname)
- except AttributeError:
- self.packer.pack_uint(PROC_UNAVAIL)
- return self.packer.get_buf()
- cred = self.unpacker.unpack_auth()
- verf = self.unpacker.unpack_auth()
- try:
- meth() # Unpack args, call turn_around(), pack reply
- except (EOFError, GarbageArgs):
- # Too few or too many arguments
- self.packer.reset()
- self.packer.pack_uint(xid)
- self.packer.pack_uint(REPLY)
- self.packer.pack_uint(MSG_ACCEPTED)
- self.packer.pack_auth((AUTH_NULL, make_auth_null()))
- self.packer.pack_uint(GARBAGE_ARGS)
- return self.packer.get_buf()
-
- def turn_around(self):
- try:
- self.unpacker.done()
- except RuntimeError:
- raise GarbageArgs
- self.packer.pack_uint(SUCCESS)
-
- def handle_0(self): # Handle NULL message
- self.turn_around()
-
- def makesocket(self):
- # This MUST be overridden
- raise RuntimeError, 'makesocket not defined'
-
- def bindsocket(self):
- # Override this to bind to a different port (e.g. reserved)
- self.sock.bind((self.host, self.port))
-
- def addpackers(self):
- # Override this to use derived classes from Packer/Unpacker
- self.packer = Packer()
- self.unpacker = Unpacker('')
-
-
-class TCPServer(Server):
-
- def makesocket(self):
- self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.prot = IPPROTO_TCP
-
- def loop(self):
- self.sock.listen(0)
- while 1:
- self.session(self.sock.accept())
-
- def session(self, connection):
- sock, (host, port) = connection
- while 1:
- try:
- call = recvrecord(sock)
- except EOFError:
- break
- except socket.error, msg:
- print 'socket error:', msg
- break
- reply = self.handle(call)
- if reply is not None:
- sendrecord(sock, reply)
-
- def forkingloop(self):
- # Like loop but uses forksession()
- self.sock.listen(0)
- while 1:
- self.forksession(self.sock.accept())
-
- def forksession(self, connection):
- # Like session but forks off a subprocess
- import os
- # Wait for deceased children
- try:
- while 1:
- pid, sts = os.waitpid(0, 1)
- except os.error:
- pass
- pid = None
- try:
- pid = os.fork()
- if pid: # Parent
- connection[0].close()
- return
- # Child
- self.session(connection)
- finally:
- # Make sure we don't fall through in the parent
- if pid == 0:
- os._exit(0)
-
-
-class UDPServer(Server):
-
- def makesocket(self):
- self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- self.prot = IPPROTO_UDP
-
- def loop(self):
- while 1:
- self.session()
-
- def session(self):
- call, host_port = self.sock.recvfrom(8192)
- reply = self.handle(call)
- if reply <> None:
- self.sock.sendto(reply, host_port)
-
-
-# Simple test program -- dump local portmapper status
-
-def test():
- pmap = UDPPortMapperClient('')
- list = pmap.Dump()
- list.sort()
- for prog, vers, prot, port in list:
- print prog, vers,
- if prot == IPPROTO_TCP: print 'tcp',
- elif prot == IPPROTO_UDP: print 'udp',
- else: print prot,
- print port
-
-
-# Test program for broadcast operation -- dump everybody's portmapper status
-
-def testbcast():
- import sys
- if sys.argv[1:]:
- bcastaddr = sys.argv[1]
- else:
- bcastaddr = ''
- def rh(reply, fromaddr):
- host, port = fromaddr
- print host + '\t' + `reply`
- pmap = BroadcastUDPPortMapperClient(bcastaddr)
- pmap.set_reply_handler(rh)
- pmap.set_timeout(5)
- replies = pmap.Getport((100002, 1, IPPROTO_UDP, 0))
-
-
-# Test program for server, with corresponding client
-# On machine A: python -c 'import rpc; rpc.testsvr()'
-# On machine B: python -c 'import rpc; rpc.testclt()' A
-# (A may be == B)
-
-def testsvr():
- # Simple test class -- proc 1 doubles its string argument as reply
- class S(UDPServer):
- def handle_1(self):
- arg = self.unpacker.unpack_string()
- self.turn_around()
- print 'RPC function 1 called, arg', `arg`
- self.packer.pack_string(arg + arg)
- #
- s = S('', 0x20000000, 1, 0)
- try:
- s.unregister()
- except RuntimeError, msg:
- print 'RuntimeError:', msg, '(ignored)'
- s.register()
- print 'Service started...'
- try:
- s.loop()
- finally:
- s.unregister()
- print 'Service interrupted.'
-
-
-def testclt():
- import sys
- if sys.argv[1:]: host = sys.argv[1]
- else: host = ''
- # Client for above server
- class C(UDPClient):
- def call_1(self, arg):
- return self.make_call(1, arg, \
- self.packer.pack_string, \
- self.unpacker.unpack_string)
- c = C(host, 0x20000000, 1)
- print 'making call...'
- reply = c.call_1('hello, world, ')
- print 'call returned', `reply`
diff --git a/Demo/rpc/test b/Demo/rpc/test
deleted file mode 100755
index ba220f24a2..0000000000
--- a/Demo/rpc/test
+++ /dev/null
@@ -1,24 +0,0 @@
-: ${PYTHON=python}
-: ${SERVER=charon.cwi.nl}
-
-set -xe
-
-$PYTHON -c 'from rpc import test; test()'
-$PYTHON -c 'from rpc import test; test()' ${SERVER}
-
-$PYTHON -c 'from rpc import testsvr; testsvr()' &
-PID=$!
-sleep 2
-$PYTHON -c 'from rpc import testclt; testclt()'
-kill -2 $PID
-
-$PYTHON -c 'from mountclient import test; test()'
-$PYTHON -c 'from mountclient import test; test()' gatekeeper.dec.com
-
-$PYTHON -c 'from nfsclient import test; test()'
-$PYTHON -c 'from nfsclient import test; test()' gatekeeper.dec.com
-$PYTHON -c 'from nfsclient import test; test()' gatekeeper.dec.com /archive
-
-$PYTHON -c 'from rnusersclient import test; test()' ''
-
-$PYTHON -c 'from rpc import testbcast; testbcast()'
diff --git a/Demo/rpc/xdr.py b/Demo/rpc/xdr.py
deleted file mode 100644
index 41c970ae91..0000000000
--- a/Demo/rpc/xdr.py
+++ /dev/null
@@ -1,201 +0,0 @@
-# Implement (a subset of) Sun XDR -- RFC1014.
-
-
-try:
- import struct
-except ImportError:
- struct = None
-
-
-Long = type(0L)
-
-
-class Packer:
-
- def __init__(self):
- self.reset()
-
- def reset(self):
- self.buf = ''
-
- def get_buf(self):
- return self.buf
-
- def pack_uint(self, x):
- self.buf = self.buf + \
- (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \
- chr(int(x>>8 & 0xff)) + chr(int(x & 0xff)))
- if struct and struct.pack('l', 1) == '\0\0\0\1':
- def pack_uint(self, x):
- if type(x) == Long:
- x = int((x + 0x80000000L) % 0x100000000L \
- - 0x80000000L)
- self.buf = self.buf + struct.pack('l', x)
-
- pack_int = pack_uint
-
- pack_enum = pack_int
-
- def pack_bool(self, x):
- if x: self.buf = self.buf + '\0\0\0\1'
- else: self.buf = self.buf + '\0\0\0\0'
-
- def pack_uhyper(self, x):
- self.pack_uint(int(x>>32 & 0xffffffff))
- self.pack_uint(int(x & 0xffffffff))
-
- pack_hyper = pack_uhyper
-
- def pack_float(self, x):
- # XXX
- self.buf = self.buf + struct.pack('f', x)
-
- def pack_double(self, x):
- # XXX
- self.buf = self.buf + struct.pack('d', x)
-
- def pack_fstring(self, n, s):
- if n < 0:
- raise ValueError, 'fstring size must be nonnegative'
- n = ((n+3)/4)*4
- data = s[:n]
- data = data + (n - len(data)) * '\0'
- self.buf = self.buf + data
-
- pack_fopaque = pack_fstring
-
- def pack_string(self, s):
- n = len(s)
- self.pack_uint(n)
- self.pack_fstring(n, s)
-
- pack_opaque = pack_string
-
- def pack_list(self, list, pack_item):
- for item in list:
- self.pack_uint(1)
- pack_item(item)
- self.pack_uint(0)
-
- def pack_farray(self, n, list, pack_item):
- if len(list) <> n:
- raise ValueError, 'wrong array size'
- for item in list:
- pack_item(item)
-
- def pack_array(self, list, pack_item):
- n = len(list)
- self.pack_uint(n)
- self.pack_farray(n, list, pack_item)
-
-
-class Unpacker:
-
- def __init__(self, data):
- self.reset(data)
-
- def reset(self, data):
- self.buf = data
- self.pos = 0
-
- def done(self):
- if self.pos < len(self.buf):
- raise RuntimeError, 'unextracted data remains'
-
- def unpack_uint(self):
- i = self.pos
- self.pos = j = i+4
- data = self.buf[i:j]
- if len(data) < 4:
- raise EOFError
- x = long(ord(data[0]))<<24 | ord(data[1])<<16 | \
- ord(data[2])<<8 | ord(data[3])
- # Return a Python long only if the value is not representable
- # as a nonnegative Python int
- if x < 0x80000000L: x = int(x)
- return x
- if struct and struct.unpack('l', '\0\0\0\1') == 1:
- def unpack_uint(self):
- i = self.pos
- self.pos = j = i+4
- data = self.buf[i:j]
- if len(data) < 4:
- raise EOFError
- return struct.unpack('l', data)
-
- def unpack_int(self):
- x = self.unpack_uint()
- if x >= 0x80000000L: x = x - 0x100000000L
- return int(x)
-
- unpack_enum = unpack_int
-
- unpack_bool = unpack_int
-
- def unpack_uhyper(self):
- hi = self.unpack_uint()
- lo = self.unpack_uint()
- return long(hi)<<32 | lo
-
- def unpack_hyper(self):
- x = self.unpack_uhyper()
- if x >= 0x8000000000000000L: x = x - 0x10000000000000000L
- return x
-
- def unpack_float(self):
- # XXX
- i = self.pos
- self.pos = j = i+4
- data = self.buf[i:j]
- if len(data) < 4:
- raise EOFError
- return struct.unpack('f', data)[0]
-
- def unpack_double(self):
- # XXX
- i = self.pos
- self.pos = j = i+8
- data = self.buf[i:j]
- if len(data) < 8:
- raise EOFError
- return struct.unpack('d', data)[0]
-
- def unpack_fstring(self, n):
- if n < 0:
- raise ValueError, 'fstring size must be nonnegative'
- i = self.pos
- j = i + (n+3)/4*4
- if j > len(self.buf):
- raise EOFError
- self.pos = j
- return self.buf[i:i+n]
-
- unpack_fopaque = unpack_fstring
-
- def unpack_string(self):
- n = self.unpack_uint()
- return self.unpack_fstring(n)
-
- unpack_opaque = unpack_string
-
- def unpack_list(self, unpack_item):
- list = []
- while 1:
- x = self.unpack_uint()
- if x == 0: break
- if x <> 1:
- raise RuntimeError, \
- '0 or 1 expected, got ' + `x`
- item = unpack_item()
- list.append(item)
- return list
-
- def unpack_farray(self, n, unpack_item):
- list = []
- for i in range(n):
- list.append(unpack_item())
- return list
-
- def unpack_array(self, unpack_item):
- n = self.unpack_uint()
- return self.unpack_farray(n, unpack_item)
diff --git a/Demo/scripts/README b/Demo/scripts/README
deleted file mode 100644
index e1cf21f231..0000000000
--- a/Demo/scripts/README
+++ /dev/null
@@ -1,19 +0,0 @@
-This directory contains a collection of executable Python scripts.
-
-See also the Tools/scripts directory!
-
-fact.py Factorize numbers
-find-uname.py Search for Unicode characters using regexps.
-from.py Summarize mailbox
-ftpstats.py Summarize ftp daemon log file
-lpwatch.py Watch BSD line printer queues
-markov.py Markov chain simulation of words or characters
-mboxconvvert.py Convert MH or MMDF mailboxes to unix mailbox format
-morse.py Produce morse code (audible or on AIFF file)
-mpzpi.py test mpz -- print digits of pi (compare pi.py)
-pi.py Print all digits of pi -- given enough time and memory
-pp.py Emulate some Perl command line options
-primes.py Print prime numbers
-script.py Equivalent to BSD script(1) -- by Steen Lumholt
-unbirthday.py Print unbirthday count
-update.py Update a bunch of files according to a script.
diff --git a/Demo/scripts/beer.py b/Demo/scripts/beer.py
deleted file mode 100644
index 1b9ac8bade..0000000000
--- a/Demo/scripts/beer.py
+++ /dev/null
@@ -1,14 +0,0 @@
-#! /usr/bin/env python
-# By GvR, demystified after a version by Fredrik Lundh.
-import sys
-n = 100
-if sys.argv[1:]: n = int(sys.argv[1])
-def bottle(n):
- if n == 0: return "no more bottles of beer"
- if n == 1: return "one bottle of beer"
- return str(n) + " bottles of beer"
-for i in range(n):
- print bottle(n-i), "on the wall,"
- print bottle(n-i) + "."
- print "Take one down, pass it around,"
- print bottle(n-i-1), "on the wall."
diff --git a/Demo/scripts/eqfix.py b/Demo/scripts/eqfix.py
deleted file mode 100755
index 583d54e0e7..0000000000
--- a/Demo/scripts/eqfix.py
+++ /dev/null
@@ -1,199 +0,0 @@
-#! /usr/bin/env python
-
-# Fix Python source files to use the new equality test operator, i.e.,
-# if x = y: ...
-# is changed to
-# if x == y: ...
-# The script correctly tokenizes the Python program to reliably
-# distinguish between assignments and equality tests.
-#
-# Command line arguments are files or directories to be processed.
-# Directories are searched recursively for files whose name looks
-# like a python module.
-# Symbolic links are always ignored (except as explicit directory
-# arguments). Of course, the original file is kept as a back-up
-# (with a "~" attached to its name).
-# It complains about binaries (files containing null bytes)
-# and about files that are ostensibly not Python files: if the first
-# line starts with '#!' and does not contain the string 'python'.
-#
-# Changes made are reported to stdout in a diff-like format.
-#
-# Undoubtedly you can do this using find and sed or perl, but this is
-# a nice example of Python code that recurses down a directory tree
-# and uses regular expressions. Also note several subtleties like
-# preserving the file's mode and avoiding to even write a temp file
-# when no changes are needed for a file.
-#
-# NB: by changing only the function fixline() you can turn this
-# into a program for a different change to Python programs...
-
-import sys
-import regex
-import os
-from stat import *
-import string
-
-err = sys.stderr.write
-dbg = err
-rep = sys.stdout.write
-
-def main():
- bad = 0
- if not sys.argv[1:]: # No arguments
- err('usage: ' + sys.argv[0] + ' file-or-directory ...\n')
- sys.exit(2)
- for arg in sys.argv[1:]:
- if os.path.isdir(arg):
- if recursedown(arg): bad = 1
- elif os.path.islink(arg):
- err(arg + ': will not process symbolic links\n')
- bad = 1
- else:
- if fix(arg): bad = 1
- sys.exit(bad)
-
-ispythonprog = regex.compile('^[a-zA-Z0-9_]+\.py$')
-def ispython(name):
- return ispythonprog.match(name) >= 0
-
-def recursedown(dirname):
- dbg('recursedown(' + `dirname` + ')\n')
- bad = 0
- try:
- names = os.listdir(dirname)
- except os.error, msg:
- err(dirname + ': cannot list directory: ' + `msg` + '\n')
- return 1
- names.sort()
- subdirs = []
- for name in names:
- if name in (os.curdir, os.pardir): continue
- fullname = os.path.join(dirname, name)
- if os.path.islink(fullname): pass
- elif os.path.isdir(fullname):
- subdirs.append(fullname)
- elif ispython(name):
- if fix(fullname): bad = 1
- for fullname in subdirs:
- if recursedown(fullname): bad = 1
- return bad
-
-def fix(filename):
-## dbg('fix(' + `filename` + ')\n')
- try:
- f = open(filename, 'r')
- except IOError, msg:
- err(filename + ': cannot open: ' + `msg` + '\n')
- return 1
- head, tail = os.path.split(filename)
- tempname = os.path.join(head, '@' + tail)
- g = None
- # If we find a match, we rewind the file and start over but
- # now copy everything to a temp file.
- lineno = 0
- while 1:
- line = f.readline()
- if not line: break
- lineno = lineno + 1
- if g is None and '\0' in line:
- # Check for binary files
- err(filename + ': contains null bytes; not fixed\n')
- f.close()
- return 1
- if lineno == 1 and g is None and line[:2] == '#!':
- # Check for non-Python scripts
- words = string.split(line[2:])
- if words and regex.search('[pP]ython', words[0]) < 0:
- msg = filename + ': ' + words[0]
- msg = msg + ' script; not fixed\n'
- err(msg)
- f.close()
- return 1
- while line[-2:] == '\\\n':
- nextline = f.readline()
- if not nextline: break
- line = line + nextline
- lineno = lineno + 1
- newline = fixline(line)
- if newline != line:
- if g is None:
- try:
- g = open(tempname, 'w')
- except IOError, msg:
- f.close()
- err(tempname+': cannot create: '+\
- `msg`+'\n')
- return 1
- f.seek(0)
- lineno = 0
- rep(filename + ':\n')
- continue # restart from the beginning
- rep(`lineno` + '\n')
- rep('< ' + line)
- rep('> ' + newline)
- if g is not None:
- g.write(newline)
-
- # End of file
- f.close()
- if not g: return 0 # No changes
-
- # Finishing touch -- move files
-
- # First copy the file's mode to the temp file
- try:
- statbuf = os.stat(filename)
- os.chmod(tempname, statbuf[ST_MODE] & 07777)
- except os.error, msg:
- err(tempname + ': warning: chmod failed (' + `msg` + ')\n')
- # Then make a backup of the original file as filename~
- try:
- os.rename(filename, filename + '~')
- except os.error, msg:
- err(filename + ': warning: backup failed (' + `msg` + ')\n')
- # Now move the temp file to the original file
- try:
- os.rename(tempname, filename)
- except os.error, msg:
- err(filename + ': rename failed (' + `msg` + ')\n')
- return 1
- # Return succes
- return 0
-
-
-from tokenize import tokenprog
-
-match = {'if':':', 'elif':':', 'while':':', 'return':'\n', \
- '(':')', '[':']', '{':'}', '`':'`'}
-
-def fixline(line):
- # Quick check for easy case
- if '=' not in line: return line
-
- i, n = 0, len(line)
- stack = []
- while i < n:
- j = tokenprog.match(line, i)
- if j < 0:
- # A bad token; forget about the rest of this line
- print '(Syntax error:)'
- print line,
- return line
- a, b = tokenprog.regs[3] # Location of the token proper
- token = line[a:b]
- i = i+j
- if stack and token == stack[-1]:
- del stack[-1]
- elif match.has_key(token):
- stack.append(match[token])
- elif token == '=' and stack:
- line = line[:a] + '==' + line[b:]
- i, n = a + len('=='), len(line)
- elif token == '==' and not stack:
- print '(Warning: \'==\' at top level:)'
- print line,
- return line
-
-
-main()
diff --git a/Demo/scripts/fact.py b/Demo/scripts/fact.py
deleted file mode 100755
index 6cc389ea6f..0000000000
--- a/Demo/scripts/fact.py
+++ /dev/null
@@ -1,48 +0,0 @@
-#! /usr/bin/env python
-
-# Factorize numbers.
-# The algorithm is not efficient, but easy to understand.
-# If there are large factors, it will take forever to find them,
-# because we try all odd numbers between 3 and sqrt(n)...
-
-import sys
-from math import sqrt
-
-error = 'fact.error' # exception
-
-def fact(n):
- if n < 1: raise error # fact() argument should be >= 1
- if n == 1: return [] # special case
- res = []
- # Treat even factors special, so we can use i = i+2 later
- while n%2 == 0:
- res.append(2)
- n = n/2
- # Try odd numbers up to sqrt(n)
- limit = sqrt(float(n+1))
- i = 3
- while i <= limit:
- if n%i == 0:
- res.append(i)
- n = n/i
- limit = sqrt(n+1)
- else:
- i = i+2
- if n != 1:
- res.append(n)
- return res
-
-def main():
- if len(sys.argv) > 1:
- for arg in sys.argv[1:]:
- n = eval(arg)
- print n, fact(n)
- else:
- try:
- while 1:
- n = input()
- print n, fact(n)
- except EOFError:
- pass
-
-main()
diff --git a/Demo/scripts/find-uname.py b/Demo/scripts/find-uname.py
deleted file mode 100644
index b76b9f0fe8..0000000000
--- a/Demo/scripts/find-uname.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/env python
-
-"""
-For each argument on the command line, look for it in the set of all Unicode
-names. Arguments are treated as case-insensitive regular expressions, e.g.:
-
- % find-uname 'small letter a$' 'horizontal line'
- *** small letter a$ matches ***
- LATIN SMALL LETTER A (97)
- COMBINING LATIN SMALL LETTER A (867)
- CYRILLIC SMALL LETTER A (1072)
- PARENTHESIZED LATIN SMALL LETTER A (9372)
- CIRCLED LATIN SMALL LETTER A (9424)
- FULLWIDTH LATIN SMALL LETTER A (65345)
- *** horizontal line matches ***
- HORIZONTAL LINE EXTENSION (9135)
-"""
-
-import unicodedata
-import sys
-import re
-
-def main(args):
- unicode_names= []
- for ix in range(sys.maxunicode+1):
- try:
- unicode_names.append( (ix, unicodedata.name(unichr(ix))) )
- except ValueError: # no name for the character
- pass
- for arg in args:
- pat = re.compile(arg, re.I)
- matches = [(x,y) for (x,y) in unicode_names
- if pat.search(y) is not None]
- if matches:
- print "***", arg, "matches", "***"
- for (x,y) in matches:
- print "%s (%d)" % (y,x)
-
-if __name__ == "__main__":
- main(sys.argv[1:])
diff --git a/Demo/scripts/from.py b/Demo/scripts/from.py
deleted file mode 100755
index d61afde06e..0000000000
--- a/Demo/scripts/from.py
+++ /dev/null
@@ -1,35 +0,0 @@
-#! /usr/bin/env python
-
-# Print From and Subject of messages in $MAIL.
-# Extension to multiple mailboxes and other bells & whistles are left
-# as exercises for the reader.
-
-import sys, os
-
-# Open mailbox file. Exits with exception when this fails.
-
-try:
- mailbox = os.environ['MAIL']
-except (AttributeError, KeyError):
- sys.stderr.write('No environment variable $MAIL\n')
- sys.exit(2)
-
-try:
- mail = open(mailbox)
-except IOError:
- sys.exit('Cannot open mailbox file: ' + mailbox)
-
-while 1:
- line = mail.readline()
- if not line:
- break # EOF
- if line.startswith('From '):
- # Start of message found
- print line[:-1],
- while 1:
- line = mail.readline()
- if not line or line == '\n':
- break
- if line.startswith('Subject: '):
- print `line[9:-1]`,
- print
diff --git a/Demo/scripts/ftpstats.py b/Demo/scripts/ftpstats.py
deleted file mode 100755
index 28b1d8bdfd..0000000000
--- a/Demo/scripts/ftpstats.py
+++ /dev/null
@@ -1,144 +0,0 @@
-#! /usr/bin/env python
-
-# Extract statistics from ftp daemon log.
-
-# Usage:
-# ftpstats [-m maxitems] [-s search] [file]
-# -m maxitems: restrict number of items in "top-N" lists, default 25.
-# -s string: restrict statistics to lines containing this string.
-# Default file is /usr/adm/ftpd; a "-" means read stdandard input.
-
-# The script must be run on the host where the ftp daemon runs.
-# (At CWI this is currently buizerd.)
-
-import os
-import sys
-import regex
-import string
-import getopt
-
-pat = '^\([a-zA-Z0-9 :]*\)!\(.*\)!\(.*\)!\([<>].*\)!\([0-9]+\)!\([0-9]+\)$'
-prog = regex.compile(pat)
-
-def main():
- maxitems = 25
- search = None
- try:
- opts, args = getopt.getopt(sys.argv[1:], 'm:s:')
- except getopt.error, msg:
- print msg
- print 'usage: ftpstats [-m maxitems] [file]'
- sys.exit(2)
- for o, a in opts:
- if o == '-m':
- maxitems = string.atoi(a)
- if o == '-s':
- search = a
- file = '/usr/adm/ftpd'
- if args: file = args[0]
- if file == '-':
- f = sys.stdin
- else:
- try:
- f = open(file, 'r')
- except IOError, msg:
- print file, ':', msg
- sys.exit(1)
- bydate = {}
- bytime = {}
- byfile = {}
- bydir = {}
- byhost = {}
- byuser = {}
- bytype = {}
- lineno = 0
- try:
- while 1:
- line = f.readline()
- if not line: break
- lineno = lineno + 1
- if search and string.find(line, search) < 0:
- continue
- if prog.match(line) < 0:
- print 'Bad line', lineno, ':', `line`
- continue
- items = prog.group(1, 2, 3, 4, 5, 6)
- (logtime, loguser, loghost, logfile, logbytes,
- logxxx2) = items
-## print logtime
-## print '-->', loguser
-## print '--> -->', loghost
-## print '--> --> -->', logfile
-## print '--> --> --> -->', logbytes
-## print '--> --> --> --> -->', logxxx2
-## for i in logtime, loghost, logbytes, logxxx2:
-## if '!' in i: print '???', i
- add(bydate, logtime[-4:] + ' ' + logtime[:6], items)
- add(bytime, logtime[7:9] + ':00-59', items)
- direction, logfile = logfile[0], logfile[1:]
- # The real path probably starts at the last //...
- while 1:
- i = string.find(logfile, '//')
- if i < 0: break
- logfile = logfile[i+1:]
- add(byfile, logfile + ' ' + direction, items)
- logdir = os.path.dirname(logfile)
-## logdir = os.path.normpath(logdir) + '/.'
- while 1:
- add(bydir, logdir + ' ' + direction, items)
- dirhead = os.path.dirname(logdir)
- if dirhead == logdir: break
- logdir = dirhead
- add(byhost, loghost, items)
- add(byuser, loguser, items)
- add(bytype, direction, items)
- except KeyboardInterrupt:
- print 'Interrupted at line', lineno
- show(bytype, 'by transfer direction', maxitems)
- show(bydir, 'by directory', maxitems)
- show(byfile, 'by file', maxitems)
- show(byhost, 'by host', maxitems)
- show(byuser, 'by user', maxitems)
- showbar(bydate, 'by date')
- showbar(bytime, 'by time of day')
-
-def showbar(dict, title):
- n = len(title)
- print '='*((70-n)/2), title, '='*((71-n)/2)
- list = []
- keys = dict.keys()
- keys.sort()
- for key in keys:
- n = len(str(key))
- list.append((len(dict[key]), key))
- maxkeylength = 0
- maxcount = 0
- for count, key in list:
- maxkeylength = max(maxkeylength, len(key))
- maxcount = max(maxcount, count)
- maxbarlength = 72 - maxkeylength - 7
- for count, key in list:
- barlength = int(round(maxbarlength*float(count)/maxcount))
- bar = '*'*barlength
- print '%5d %-*s %s' % (count, maxkeylength, key, bar)
-
-def show(dict, title, maxitems):
- if len(dict) > maxitems:
- title = title + ' (first %d)'%maxitems
- n = len(title)
- print '='*((70-n)/2), title, '='*((71-n)/2)
- list = []
- keys = dict.keys()
- for key in keys:
- list.append((-len(dict[key]), key))
- list.sort()
- for count, key in list[:maxitems]:
- print '%5d %s' % (-count, key)
-
-def add(dict, key, item):
- if dict.has_key(key):
- dict[key].append(item)
- else:
- dict[key] = [item]
-
-main()
diff --git a/Demo/scripts/lpwatch.py b/Demo/scripts/lpwatch.py
deleted file mode 100755
index 9f051ebbf3..0000000000
--- a/Demo/scripts/lpwatch.py
+++ /dev/null
@@ -1,109 +0,0 @@
-#! /usr/bin/env python
-
-# Watch line printer queue(s).
-# Intended for BSD 4.3 lpq.
-
-import posix
-import sys
-import time
-import string
-
-DEF_PRINTER = 'psc'
-DEF_DELAY = 10
-
-def main():
- delay = DEF_DELAY # XXX Use getopt() later
- try:
- thisuser = posix.environ['LOGNAME']
- except:
- thisuser = posix.environ['USER']
- printers = sys.argv[1:]
- if printers:
- # Strip '-P' from printer names just in case
- # the user specified it...
- for i in range(len(printers)):
- if printers[i][:2] == '-P':
- printers[i] = printers[i][2:]
- else:
- if posix.environ.has_key('PRINTER'):
- printers = [posix.environ['PRINTER']]
- else:
- printers = [DEF_PRINTER]
- #
- clearhome = posix.popen('clear', 'r').read()
- #
- while 1:
- text = clearhome
- for name in printers:
- text = text + makestatus(name, thisuser) + '\n'
- print text
- time.sleep(delay)
-
-def makestatus(name, thisuser):
- pipe = posix.popen('lpq -P' + name + ' 2>&1', 'r')
- lines = []
- users = {}
- aheadbytes = 0
- aheadjobs = 0
- userseen = 0
- totalbytes = 0
- totaljobs = 0
- while 1:
- line = pipe.readline()
- if not line: break
- fields = string.split(line)
- n = len(fields)
- if len(fields) >= 6 and fields[n-1] == 'bytes':
- rank = fields[0]
- user = fields[1]
- job = fields[2]
- files = fields[3:-2]
- bytes = eval(fields[n-2])
- if user == thisuser:
- userseen = 1
- elif not userseen:
- aheadbytes = aheadbytes + bytes
- aheadjobs = aheadjobs + 1
- totalbytes = totalbytes + bytes
- totaljobs = totaljobs + 1
- if users.has_key(user):
- ujobs, ubytes = users[user]
- else:
- ujobs, ubytes = 0, 0
- ujobs = ujobs + 1
- ubytes = ubytes + bytes
- users[user] = ujobs, ubytes
- else:
- if fields and fields[0] <> 'Rank':
- line = string.strip(line)
- if line == 'no entries':
- line = name + ': idle'
- elif line[-22:] == ' is ready and printing':
- line = name
- lines.append(line)
- #
- if totaljobs:
- line = `(totalbytes+1023)/1024` + ' K'
- if totaljobs <> len(users):
- line = line + ' (' + `totaljobs` + ' jobs)'
- if len(users) == 1:
- line = line + ' for ' + users.keys()[0]
- else:
- line = line + ' for ' + `len(users)` + ' users'
- if userseen:
- if aheadjobs == 0:
- line = line + ' (' + thisuser + ' first)'
- else:
- line = line + ' (' + `(aheadbytes+1023)/1024`
- line = line + ' K before ' + thisuser + ')'
- lines.append(line)
- #
- sts = pipe.close()
- if sts:
- lines.append('lpq exit status ' + `sts`)
- return string.joinfields(lines, ': ')
-
-try:
- main()
-except KeyboardInterrupt:
- pass
diff --git a/Demo/scripts/makedir.py b/Demo/scripts/makedir.py
deleted file mode 100755
index 4c00d88809..0000000000
--- a/Demo/scripts/makedir.py
+++ /dev/null
@@ -1,20 +0,0 @@
-#! /usr/bin/env python
-
-# Like mkdir, but also make intermediate directories if necessary.
-# It is not an error if the given directory already exists (as long
-# as it is a directory).
-# Errors are not treated specially -- you just get a Python exception.
-
-import sys, os
-
-def main():
- for p in sys.argv[1:]:
- makedirs(p)
-
-def makedirs(p):
- if p and not os.path.isdir(p):
- head, tail = os.path.split(p)
- makedirs(head)
- os.mkdir(p, 0777)
-
-main()
diff --git a/Demo/scripts/markov.py b/Demo/scripts/markov.py
deleted file mode 100755
index e1649f1e9d..0000000000
--- a/Demo/scripts/markov.py
+++ /dev/null
@@ -1,116 +0,0 @@
-#! /usr/bin/env python
-
-class Markov:
- def __init__(self, histsize, choice):
- self.histsize = histsize
- self.choice = choice
- self.trans = {}
- def add(self, state, next):
- if not self.trans.has_key(state):
- self.trans[state] = [next]
- else:
- self.trans[state].append(next)
- def put(self, seq):
- n = self.histsize
- add = self.add
- add(None, seq[:0])
- for i in range(len(seq)):
- add(seq[max(0, i-n):i], seq[i:i+1])
- add(seq[len(seq)-n:], None)
- def get(self):
- choice = self.choice
- trans = self.trans
- n = self.histsize
- seq = choice(trans[None])
- while 1:
- subseq = seq[max(0, len(seq)-n):]
- options = trans[subseq]
- next = choice(options)
- if not next: break
- seq = seq + next
- return seq
-
-def test():
- import sys, string, random, getopt
- args = sys.argv[1:]
- try:
- opts, args = getopt.getopt(args, '0123456789cdw')
- except getopt.error:
- print 'Usage: markov [-#] [-cddqw] [file] ...'
- print 'Options:'
- print '-#: 1-digit history size (default 2)'
- print '-c: characters (default)'
- print '-w: words'
- print '-d: more debugging output'
- print '-q: no debugging output'
- print 'Input files (default stdin) are split in paragraphs'
- print 'separated blank lines and each paragraph is split'
- print 'in words by whitespace, then reconcatenated with'
- print 'exactly one space separating words.'
- print 'Output consists of paragraphs separated by blank'
- print 'lines, where lines are no longer than 72 characters.'
- histsize = 2
- do_words = 0
- debug = 1
- for o, a in opts:
- if '-0' <= o <= '-9': histsize = eval(o[1:])
- if o == '-c': do_words = 0
- if o == '-d': debug = debug + 1
- if o == '-q': debug = 0
- if o == '-w': do_words = 1
- if not args: args = ['-']
- m = Markov(histsize, random.choice)
- try:
- for filename in args:
- if filename == '-':
- f = sys.stdin
- if f.isatty():
- print 'Sorry, need stdin from file'
- continue
- else:
- f = open(filename, 'r')
- if debug: print 'processing', filename, '...'
- text = f.read()
- f.close()
- paralist = string.splitfields(text, '\n\n')
- for para in paralist:
- if debug > 1: print 'feeding ...'
- words = string.split(para)
- if words:
- if do_words: data = tuple(words)
- else: data = string.joinfields(words, ' ')
- m.put(data)
- except KeyboardInterrupt:
- print 'Interrupted -- continue with data read so far'
- if not m.trans:
- print 'No valid input files'
- return
- if debug: print 'done.'
- if debug > 1:
- for key in m.trans.keys():
- if key is None or len(key) < histsize:
- print `key`, m.trans[key]
- if histsize == 0: print `''`, m.trans['']
- print
- while 1:
- data = m.get()
- if do_words: words = data
- else: words = string.split(data)
- n = 0
- limit = 72
- for w in words:
- if n + len(w) > limit:
- print
- n = 0
- print w,
- n = n + len(w) + 1
- print
- print
-
-def tuple(list):
- if len(list) == 0: return ()
- if len(list) == 1: return (list[0],)
- i = len(list)/2
- return tuple(list[:i]) + tuple(list[i:])
-
-test()
diff --git a/Demo/scripts/mboxconvert.py b/Demo/scripts/mboxconvert.py
deleted file mode 100755
index 08e0d0cbe5..0000000000
--- a/Demo/scripts/mboxconvert.py
+++ /dev/null
@@ -1,123 +0,0 @@
-#! /usr/bin/env python
-
-# Convert MH directories (1 message per file) or MMDF mailboxes (4x^A
-# delimited) to unix mailbox (From ... delimited) on stdout.
-# If -f is given, files contain one message per file (e.g. MH messages)
-
-import rfc822
-import sys
-import time
-import os
-import stat
-import getopt
-import regex
-
-def main():
- dofile = mmdf
- try:
- opts, args = getopt.getopt(sys.argv[1:], 'f')
- except getopt.error, msg:
- sys.stderr.write('%s\n' % msg)
- sys.exit(2)
- for o, a in opts:
- if o == '-f':
- dofile = message
- if not args:
- args = ['-']
- sts = 0
- for arg in args:
- if arg == '-' or arg == '':
- sts = dofile(sys.stdin) or sts
- elif os.path.isdir(arg):
- sts = mh(arg) or sts
- elif os.path.isfile(arg):
- try:
- f = open(arg)
- except IOError, msg:
- sys.stderr.write('%s: %s\n' % (arg, msg))
- sts = 1
- continue
- sts = dofile(f) or sts
- f.close()
- else:
- sys.stderr.write('%s: not found\n' % arg)
- sts = 1
- if sts:
- sys.exit(sts)
-
-numeric = regex.compile('[1-9][0-9]*')
-
-def mh(dir):
- sts = 0
- msgs = os.listdir(dir)
- for msg in msgs:
- if numeric.match(msg) != len(msg):
- continue
- fn = os.path.join(dir, msg)
- try:
- f = open(fn)
- except IOError, msg:
- sys.stderr.write('%s: %s\n' % (fn, msg))
- sts = 1
- continue
- sts = message(f) or sts
- return sts
-
-def mmdf(f):
- sts = 0
- while 1:
- line = f.readline()
- if not line:
- break
- if line == '\1\1\1\1\n':
- sts = message(f, line) or sts
- else:
- sys.stderr.write(
- 'Bad line in MMFD mailbox: %s\n' % `line`)
- return sts
-
-counter = 0 # for generating unique Message-ID headers
-
-def message(f, delimiter = ''):
- sts = 0
- # Parse RFC822 header
- m = rfc822.Message(f)
- # Write unix header line
- fullname, email = m.getaddr('From')
- tt = m.getdate('Date')
- if tt:
- t = time.mktime(tt)
- else:
- sys.stderr.write(
- 'Unparseable date: %s\n' % `m.getheader('Date')`)
- t = os.fstat(f.fileno())[stat.ST_MTIME]
- print 'From', email, time.ctime(t)
- # Copy RFC822 header
- for line in m.headers:
- print line,
- # Invent Message-ID header if none is present
- if not m.has_key('message-id'):
- global counter
- counter = counter + 1
- msgid = "<%s.%d>" % (hex(t), counter)
- sys.stderr.write("Adding Message-ID %s (From %s)\n" %
- (msgid, email))
- print "Message-ID:", msgid
- print
- # Copy body
- while 1:
- line = f.readline()
- if line == delimiter:
- break
- if not line:
- sys.stderr.write('Unexpected EOF in message\n')
- sts = 1
- break
- if line[:5] == 'From ':
- line = '>' + line
- print line,
- # Print trailing newline
- print
- return sts
-
-main()
diff --git a/Demo/scripts/mkrcs.py b/Demo/scripts/mkrcs.py
deleted file mode 100755
index 36a35eace2..0000000000
--- a/Demo/scripts/mkrcs.py
+++ /dev/null
@@ -1,60 +0,0 @@
-#! /usr/bin/env python
-
-# A rather specialized script to make sure that a symbolic link named
-# RCS exists pointing to a real RCS directory in a parallel tree
-# referenced as RCStree in an ancestor directory.
-# (I use this because I like my RCS files to reside on a physically
-# different machine).
-
-import os
-
-def main():
- rcstree = 'RCStree'
- rcs = 'RCS'
- if os.path.islink(rcs):
- print `rcs`, 'is a symlink to', `os.readlink(rcs)`
- return
- if os.path.isdir(rcs):
- print `rcs`, 'is an ordinary directory'
- return
- if os.path.exists(rcs):
- print `rcs`, 'is a file?!?!'
- return
- #
- p = os.getcwd()
- up = ''
- down = ''
- # Invariants:
- # (1) join(p, down) is the current directory
- # (2) up is the same directory as p
- # Ergo:
- # (3) join(up, down) is the current directory
- #print 'p =', `p`
- while not os.path.isdir(os.path.join(p, rcstree)):
- head, tail = os.path.split(p)
- #print 'head =', `head`, '; tail =', `tail`
- if not tail:
- print 'Sorry, no ancestor dir contains', `rcstree`
- return
- p = head
- up = os.path.join(os.pardir, up)
- down = os.path.join(tail, down)
- #print 'p =', `p`, '; up =', `up`, '; down =', `down`
- there = os.path.join(up, rcstree)
- there = os.path.join(there, down)
- there = os.path.join(there, rcs)
- if os.path.isdir(there):
- print `there`, 'already exists'
- else:
- print 'making', `there`
- makedirs(there)
- print 'making symlink', `rcs`, '->', `there`
- os.symlink(there, rcs)
-
-def makedirs(p):
- if not os.path.isdir(p):
- head, tail = os.path.split(p)
- makedirs(head)
- os.mkdir(p, 0777)
-
-main()
diff --git a/Demo/scripts/morse.py b/Demo/scripts/morse.py
deleted file mode 100755
index 2cea83e402..0000000000
--- a/Demo/scripts/morse.py
+++ /dev/null
@@ -1,149 +0,0 @@
-# DAH should be three DOTs.
-# Space between DOTs and DAHs should be one DOT.
-# Space between two letters should be one DAH.
-# Space between two words should be DOT DAH DAH.
-
-import sys, math, audiodev
-
-DOT = 30
-DAH = 3 * DOT
-OCTAVE = 2 # 1 == 441 Hz, 2 == 882 Hz, ...
-
-morsetab = {
- 'A': '.-', 'a': '.-',
- 'B': '-...', 'b': '-...',
- 'C': '-.-.', 'c': '-.-.',
- 'D': '-..', 'd': '-..',
- 'E': '.', 'e': '.',
- 'F': '..-.', 'f': '..-.',
- 'G': '--.', 'g': '--.',
- 'H': '....', 'h': '....',
- 'I': '..', 'i': '..',
- 'J': '.---', 'j': '.---',
- 'K': '-.-', 'k': '-.-',
- 'L': '.-..', 'l': '.-..',
- 'M': '--', 'm': '--',
- 'N': '-.', 'n': '-.',
- 'O': '---', 'o': '---',
- 'P': '.--.', 'p': '.--.',
- 'Q': '--.-', 'q': '--.-',
- 'R': '.-.', 'r': '.-.',
- 'S': '...', 's': '...',
- 'T': '-', 't': '-',
- 'U': '..-', 'u': '..-',
- 'V': '...-', 'v': '...-',
- 'W': '.--', 'w': '.--',
- 'X': '-..-', 'x': '-..-',
- 'Y': '-.--', 'y': '-.--',
- 'Z': '--..', 'z': '--..',
- '0': '-----',
- '1': '.----',
- '2': '..---',
- '3': '...--',
- '4': '....-',
- '5': '.....',
- '6': '-....',
- '7': '--...',
- '8': '---..',
- '9': '----.',
- ',': '--..--',
- '.': '.-.-.-',
- '?': '..--..',
- ';': '-.-.-.',
- ':': '---...',
- "'": '.----.',
- '-': '-....-',
- '/': '-..-.',
- '(': '-.--.-',
- ')': '-.--.-',
- '_': '..--.-',
- ' ': ' '
-}
-
-# If we play at 44.1 kHz (which we do), then if we produce one sine
-# wave in 100 samples, we get a tone of 441 Hz. If we produce two
-# sine waves in these 100 samples, we get a tone of 882 Hz. 882 Hz
-# appears to be a nice one for playing morse code.
-def mkwave(octave):
- global sinewave, nowave
- sinewave = ''
- for i in range(100):
- val = int(math.sin(math.pi * float(i) * octave / 50.0) * 30000)
- sinewave = sinewave + chr((val >> 8) & 255) + chr(val & 255)
- nowave = '\0' * 200
-
-mkwave(OCTAVE)
-
-def main():
- import getopt, string
- try:
- opts, args = getopt.getopt(sys.argv[1:], 'o:p:')
- except getopt.error:
- sys.stderr.write('Usage ' + sys.argv[0] +
- ' [ -o outfile ] [ args ] ...\n')
- sys.exit(1)
- dev = None
- for o, a in opts:
- if o == '-o':
- import aifc
- dev = aifc.open(a, 'w')
- dev.setframerate(44100)
- dev.setsampwidth(2)
- dev.setnchannels(1)
- if o == '-p':
- mkwave(string.atoi(a))
- if not dev:
- import audiodev
- dev = audiodev.AudioDev()
- dev.setoutrate(44100)
- dev.setsampwidth(2)
- dev.setnchannels(1)
- dev.close = dev.stop
- dev.writeframesraw = dev.writeframes
- if args:
- line = string.join(args)
- else:
- line = sys.stdin.readline()
- while line:
- mline = morse(line)
- play(mline, dev)
- if hasattr(dev, 'wait'):
- dev.wait()
- if not args:
- line = sys.stdin.readline()
- else:
- line = ''
- dev.close()
-
-# Convert a string to morse code with \001 between the characters in
-# the string.
-def morse(line):
- res = ''
- for c in line:
- try:
- res = res + morsetab[c] + '\001'
- except KeyError:
- pass
- return res
-
-# Play a line of morse code.
-def play(line, dev):
- for c in line:
- if c == '.':
- sine(dev, DOT)
- elif c == '-':
- sine(dev, DAH)
- else: # space
- pause(dev, DAH + DOT)
- pause(dev, DOT)
-
-def sine(dev, length):
- for i in range(length):
- dev.writeframesraw(sinewave)
-
-def pause(dev, length):
- for i in range(length):
- dev.writeframesraw(nowave)
-
-if __name__ == '__main__' or sys.argv[0] == __name__:
- main()
diff --git a/Demo/scripts/mpzpi.py b/Demo/scripts/mpzpi.py
deleted file mode 100755
index 93c74aa398..0000000000
--- a/Demo/scripts/mpzpi.py
+++ /dev/null
@@ -1,34 +0,0 @@
-#! /usr/bin/env python
-# Print digits of pi forever.
-#
-# The algorithm, using Python's 'long' integers ("bignums"), works
-# with continued fractions, and was conceived by Lambert Meertens.
-#
-# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
-# published by Prentice-Hall (UK) Ltd., 1990.
-
-import sys
-from mpz import mpz
-
-def main():
- mpzone, mpztwo, mpzten = mpz(1), mpz(2), mpz(10)
- k, a, b, a1, b1 = mpz(2), mpz(4), mpz(1), mpz(12), mpz(4)
- while 1:
- # Next approximation
- p, q, k = k*k, mpztwo*k+mpzone, k+mpzone
- a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
- # Print common digits
- d, d1 = a/b, a1/b1
- while d == d1:
- output(d)
- a, a1 = mpzten*(a%b), mpzten*(a1%b1)
- d, d1 = a/b, a1/b1
-
-def output(d):
- # Use write() to avoid spaces between the digits
- # Use int(d) to avoid a trailing L after each digit
- sys.stdout.write(`int(d)`)
- # Flush so the output is seen immediately
- sys.stdout.flush()
-
-main()
diff --git a/Demo/scripts/newslist.doc b/Demo/scripts/newslist.doc
deleted file mode 100755
index 87fd9ba27a..0000000000
--- a/Demo/scripts/newslist.doc
+++ /dev/null
@@ -1,59 +0,0 @@
- NEWSLIST
- ========
- A program to assist HTTP browsing of newsgroups
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-WWW browsers such as NCSA Mosaic allow the user to read newsgroup
-articles by specifying the group name in a URL eg 'news:comp.answers'.
-
-To browse through many groups, though, (and there are several thousand
-of them) you really need a page or pages containing links to all the
-groups. There are some good ones out there, for example,
-
- http://info.cern.ch/hypertext/DataSources/News/Groups/Overview.html
-
-is the standard one at CERN, but it only shows the groups available there,
-which may be rather different from those available on your machine.
-
-Newslist is a program which creates a hierarchy of pages for you based
-on the groups available from YOUR server. It is written in python - a
-splendid interpreted object-oriented language which I suggest you get
-right now from the directory /pub/python at ftp.cwi.nl, if you haven't
-already got it.
-
-You should be able to see some sample output by looking at:
- http://pelican.cl.cam.ac.uk/newspage/root.html
-
-Descriptions of newsgroups can be added from a file with one group
-per line. eg:
-
- alt.foo Articles about foo
- comp.bar Programming in 'bar' and related languages
-
-A suitable list detailing most groups can be found at ftp.uu.net in
-/uunet-info/newsgroups.gz.
-
-Make sure you read the information at the beginning of the program source and
-configure the variables before running.
-
-In addition to python, you need:
-
- An NNTP-based news feed.
- A directory in which to put the pages.
-
-The programming is not very beautiful, but it works! It comes with no
-warranty, express or implied, but with the hope that some others may
-find it useful.
-
-Comments, improvements & suggestions welcomed.
-Quentin Stafford-Fraser
-
- ----------------------------------------------------------------------
- Quentin Stafford-Fraser
- http://pelican.cl.cam.ac.uk/people/qs101/me.html
-
- Cambridge University Computer Lab Rank Xerox Cambridge EuroPARC
- qs101@cl.cam.ac.uk fraser@europarc.xerox.com
- Tel: +44 223 334411 Tel: +44 223 341521
- Fax: +44 223 334679 Fax: +44 223 341510
- ----------------------------------------------------------------------
diff --git a/Demo/scripts/newslist.py b/Demo/scripts/newslist.py
deleted file mode 100755
index f78ca30271..0000000000
--- a/Demo/scripts/newslist.py
+++ /dev/null
@@ -1,366 +0,0 @@
-#! /usr/bin/env python
-#######################################################################
-# Newslist $Revision$
-#
-# Syntax:
-# newslist [ -a ]
-#
-# This is a program to create a directory full of HTML pages
-# which between them contain links to all the newsgroups available
-# on your server.
-#
-# The -a option causes a complete list of all groups to be read from
-# the server rather than just the ones which have appeared since last
-# execution. This recreates the local list from scratch. Use this on
-# the first invocation of the program, and from time to time thereafter.
-# When new groups are first created they may appear on your server as
-# empty groups. By default, empty groups are ignored by the -a option.
-# However, these new groups will not be created again, and so will not
-# appear in the server's list of 'new groups' at a later date. Hence it
-# won't appear until you do a '-a' after some articles have appeared.
-#
-# I should really keep a list of ignored empty groups and re-check them
-# for articles on every run, but I haven't got around to it yet.
-#
-# This assumes an NNTP news feed.
-#
-# Feel free to copy, distribute and modify this code for
-# non-commercial use. If you make any useful modifications, let me
-# know!
-#
-# (c) Quentin Stafford-Fraser 1994
-# fraser@europarc.xerox.com qs101@cl.cam.ac.uk
-# #
-#######################################################################
-import sys,nntplib, string, marshal, time, os, posix, string
-
-#######################################################################
-# Check these variables before running! #
-
-# Top directory.
-# Filenames which don't start with / are taken as being relative to this.
-topdir='/anfs/qsbigdisc/web/html/newspage'
-
-# The name of your NNTP host
-# eg.
-# newshost = 'nntp-serv.cl.cam.ac.uk'
-# or use following to get the name from the NNTPSERVER environment
-# variable:
-# newshost = posix.environ['NNTPSERVER']
-newshost = 'nntp-serv.cl.cam.ac.uk'
-
-# The filename for a local cache of the newsgroup list
-treefile = 'grouptree'
-
-# The filename for descriptions of newsgroups
-# I found a suitable one at ftp.uu.net in /uunet-info/newgroups.gz
-# You can set this to '' if you don't wish to use one.
-descfile = 'newsgroups'
-
-# The directory in which HTML pages should be created
-# eg.
-# pagedir = '/usr/local/lib/html/newspage'
-# pagedir = 'pages'
-pagedir = topdir
-
-# The html prefix which will refer to this directory
-# eg.
-# httppref = '/newspage/',
-# or leave blank for relative links between pages: (Recommended)
-# httppref = ''
-httppref = ''
-
-# The name of the 'root' news page in this directory.
-# A .html suffix will be added.
-rootpage = 'root'
-
-# Set skipempty to 0 if you wish to see links to empty groups as well.
-# Only affects the -a option.
-skipempty = 1
-
-# pagelinkicon can contain html to put an icon after links to
-# further pages. This helps to make important links stand out.
-# Set to '' if not wanted, or '...' is quite a good one.
-pagelinkicon='... '
-
-# ---------------------------------------------------------------------
-# Less important personal preferences:
-
-# Sublistsize controls the maximum number of items the will appear as
-# an indented sub-list before the whole thing is moved onto a different
-# page. The smaller this is, the more pages you will have, but the
-# shorter each will be.
-sublistsize = 4
-
-# That should be all. #
-#######################################################################
-
-for dir in os.curdir, os.environ['HOME']:
- rcfile = os.path.join(dir, '.newslistrc.py')
- if os.path.exists(rcfile):
- print rcfile
- execfile(rcfile)
- break
-
-from nntplib import NNTP
-from stat import *
-
-rcsrev = '$Revision$'
-rcsrev = string.join(filter(lambda s: '$' not in s, string.split(rcsrev)))
-desc = {}
-
-# Make (possibly) relative filenames into absolute ones
-treefile = os.path.join(topdir,treefile)
-descfile = os.path.join(topdir,descfile)
-page = os.path.join(topdir,pagedir)
-
-# First the bits for creating trees ---------------------------
-
-# Addtotree creates/augments a tree from a list of group names
-def addtotree(tree, groups):
- print 'Updating tree...'
- for i in groups:
- parts = string.splitfields(i,'.')
- makeleaf(tree, parts)
-
-# Makeleaf makes a leaf and the branch leading to it if necessary
-def makeleaf(tree,path):
- j = path[0]
- l = len(path)
-
- if not tree.has_key(j):
- tree[j] = {}
- if l == 1:
- tree[j]['.'] = '.'
- if l > 1:
- makeleaf(tree[j],path[1:])
-
-# Then the bits for outputting trees as pages ----------------
-
-# Createpage creates an HTML file named .html containing links
-# to those groups beginning with .
-
-def createpage(root, tree, p):
- filename = os.path.join(pagedir,root+'.html')
- if root == rootpage:
- detail = ''
- else:
- detail = ' under ' + root
- f = open(filename,'w')
- # f.write('Content-Type: text/html\n')
- f.write('Newsgroups available' + detail + '\n')
- f.write('
\n')
- printtree(f,tree,0,p)
- f.write('This page automatically created by \'newslist\' v. '+rcsrev+'.')
- f.write(time.ctime(time.time()) + '
')
- f.close()
-
-# Printtree prints the groups as a bulleted list. Groups with
-# more than subgroups will be put on a separate page.
-# Other sets of subgroups are just indented.
-
-def printtree(f, tree, indent, p):
- global desc
- l = len(tree)
-
- if l > sublistsize and indent>0:
- # Create a new page and a link to it
- f.write('
')
- f.write(p[1:]+'.*')
- f.write(''+pagelinkicon+'\n')
- createpage(p[1:], tree, p)
- return
-
- kl = tree.keys()
-
- if l > 1:
- kl.sort()
- if indent > 0:
- # Create a sub-list
- f.write('
'+p[1:]+'\n
')
- else:
- # Create a main list
- f.write('
')
- indent = indent + 1
-
- for i in kl:
- if i == '.':
- # Output a newsgroup
- f.write('
'+ p[1:] + ' ')
- if desc.has_key(p[1:]):
- f.write(' '+desc[p[1:]]+'\n')
- else:
- f.write('\n')
- else:
- # Output a hierarchy
- printtree(f,tree[i], indent, p+'.'+i)
-
- if l > 1:
- f.write('\n
')
-
-# Reading descriptions file ---------------------------------------
-
-# This returns an array mapping group name to its description
-
-def readdesc(descfile):
- global desc
-
- desc = {}
-
- if descfile == '':
- return
-
- try:
- d = open(descfile, 'r')
- print 'Reading descriptions...'
- except (IOError):
- print 'Failed to open description file ' + descfile
- return
- l = d.readline()
- while l != '':
- bits = string.split(l)
- try:
- grp = bits[0]
- dsc = string.join(bits[1:])
- if len(dsc)>1:
- desc[grp] = dsc
- except (IndexError):
- pass
- l = d.readline()
-
-# Check that ouput directory exists, ------------------------------
-# and offer to create it if not
-
-def checkopdir(pagedir):
- if not os.path.isdir(pagedir):
- print 'Directory '+pagedir+' does not exist.'
- print 'Shall I create it for you? (y/n)'
- if sys.stdin.readline()[0] == 'y':
- try:
- os.mkdir(pagedir,0777)
- except:
- print 'Sorry - failed!'
- sys.exit(1)
- else:
- print 'OK. Exiting.'
- sys.exit(1)
-
-# Read and write current local tree ----------------------------------
-
-def readlocallist(treefile):
- print 'Reading current local group list...'
- tree = {}
- try:
- treetime = time.localtime(os.stat(treefile)[ST_MTIME])
- except:
- print '\n*** Failed to open local group cache '+treefile
- print 'If this is the first time you have run newslist, then'
- print 'use the -a option to create it.'
- sys.exit(1)
- treedate = '%02d%02d%02d' % (treetime[0] % 100 ,treetime[1], treetime[2])
- try:
- dump = open(treefile,'r')
- tree = marshal.load(dump)
- dump.close()
- except (IOError):
- print 'Cannot open local group list ' + treefile
- return (tree, treedate)
-
-def writelocallist(treefile, tree):
- try:
- dump = open(treefile,'w')
- groups = marshal.dump(tree,dump)
- dump.close()
- print 'Saved list to '+treefile+'\n'
- except:
- print 'Sorry - failed to write to local group cache '+treefile
- print 'Does it (or its directory) have the correct permissions?'
- sys.exit(1)
-
-# Return list of all groups on server -----------------------------
-
-def getallgroups(server):
- print 'Getting list of all groups...'
- treedate='010101'
- info = server.list()[1]
- groups = []
- print 'Processing...'
- if skipempty:
- print '\nIgnoring following empty groups:'
- for i in info:
- grpname = string.split(i[0])[0]
- if skipempty and string.atoi(i[1]) < string.atoi(i[2]):
- print grpname+' ',
- else:
- groups.append(grpname)
- print '\n'
- if skipempty:
- print '(End of empty groups)'
- return groups
-
-# Return list of new groups on server -----------------------------
-
-def getnewgroups(server, treedate):
- print 'Getting list of new groups since start of '+treedate+'...',
- info = server.newgroups(treedate,'000001')[1]
- print 'got '+`len(info)`+'.'
- print 'Processing...',
- groups = []
- for i in info:
- grpname = string.split(i)[0]
- groups.append(grpname)
- print 'Done'
- return groups
-
-# Now the main program --------------------------------------------
-
-def main():
- global desc
-
- tree={}
-
- # Check that the output directory exists
- checkopdir(pagedir);
-
- try:
- print 'Connecting to '+newshost+'...'
- if sys.version[0] == '0':
- s = NNTP.init(newshost)
- else:
- s = NNTP(newshost)
- connected = 1
- except (nntplib.error_temp, nntplib.error_perm), x:
- print 'Error connecting to host:', x
- print 'I\'ll try to use just the local list.'
- connected = 0
-
- # If -a is specified, read the full list of groups from server
- if connected and len(sys.argv) > 1 and sys.argv[1] == '-a':
-
- groups = getallgroups(s)
-
- # Otherwise just read the local file and then add
- # groups created since local file last modified.
- else:
-
- (tree, treedate) = readlocallist(treefile)
- if connected:
- groups = getnewgroups(s, treedate)
-
- if connected:
- addtotree(tree, groups)
- writelocallist(treefile,tree)
-
- # Read group descriptions
- readdesc(descfile)
-
- print 'Creating pages...'
- createpage(rootpage, tree, '')
- print 'Done'
-
-
-main()
-
-# That's all folks
-######################################################################
diff --git a/Demo/scripts/pi.py b/Demo/scripts/pi.py
deleted file mode 100755
index d6337238a8..0000000000
--- a/Demo/scripts/pi.py
+++ /dev/null
@@ -1,33 +0,0 @@
-#! /usr/bin/env python
-
-# Print digits of pi forever.
-#
-# The algorithm, using Python's 'long' integers ("bignums"), works
-# with continued fractions, and was conceived by Lambert Meertens.
-#
-# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
-# published by Prentice-Hall (UK) Ltd., 1990.
-
-import sys
-
-def main():
- k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
- while 1:
- # Next approximation
- p, q, k = k*k, 2L*k+1L, k+1L
- a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
- # Print common digits
- d, d1 = a/b, a1/b1
- while d == d1:
- output(d)
- a, a1 = 10L*(a%b), 10L*(a1%b1)
- d, d1 = a/b, a1/b1
-
-def output(d):
- # Use write() to avoid spaces between the digits
- # Use str() to avoid the 'L'
- sys.stdout.write(str(d))
- # Flush so the output is seen immediately
- sys.stdout.flush()
-
-main()
diff --git a/Demo/scripts/pp.py b/Demo/scripts/pp.py
deleted file mode 100755
index 64e57ee15f..0000000000
--- a/Demo/scripts/pp.py
+++ /dev/null
@@ -1,130 +0,0 @@
-#! /usr/bin/env python
-
-# Emulate some Perl command line options.
-# Usage: pp [-a] [-c] [-d] [-e scriptline] [-F fieldsep] [-n] [-p] [file] ...
-# Where the options mean the following:
-# -a : together with -n or -p, splits each line into list F
-# -c : check syntax only, do not execute any code
-# -d : run the script under the debugger, pdb
-# -e scriptline : gives one line of the Python script; may be repeated
-# -F fieldsep : sets the field separator for the -a option [not in Perl]
-# -n : runs the script for each line of input
-# -p : prints the line after the script has run
-# When no script lines have been passed, the first file argument
-# contains the script. With -n or -p, the remaining arguments are
-# read as input to the script, line by line. If a file is '-'
-# or missing, standard input is read.
-
-# XXX To do:
-# - add -i extension option (change files in place)
-# - make a single loop over the files and lines (changes effect of 'break')?
-# - add an option to specify the record separator
-# - except for -n/-p, run directly from the file if at all possible
-
-import sys
-import string
-import getopt
-
-FS = ''
-SCRIPT = []
-AFLAG = 0
-CFLAG = 0
-DFLAG = 0
-NFLAG = 0
-PFLAG = 0
-
-try:
- optlist, ARGS = getopt.getopt(sys.argv[1:], 'acde:F:np')
-except getopt.error, msg:
- sys.stderr.write(sys.argv[0] + ': ' + msg + '\n')
- sys.exit(2)
-
-for option, optarg in optlist:
- if option == '-a':
- AFLAG = 1
- elif option == '-c':
- CFLAG = 1
- elif option == '-d':
- DFLAG = 1
- elif option == '-e':
- for line in string.splitfields(optarg, '\n'):
- SCRIPT.append(line)
- elif option == '-F':
- FS = optarg
- elif option == '-n':
- NFLAG = 1
- PFLAG = 0
- elif option == '-p':
- NFLAG = 1
- PFLAG = 1
- else:
- print option, 'not recognized???'
-
-if not ARGS: ARGS.append('-')
-
-if not SCRIPT:
- if ARGS[0] == '-':
- fp = sys.stdin
- else:
- fp = open(ARGS[0], 'r')
- while 1:
- line = fp.readline()
- if not line: break
- SCRIPT.append(line[:-1])
- del fp
- del ARGS[0]
- if not ARGS: ARGS.append('-')
-
-if CFLAG:
- prologue = ['if 0:']
- epilogue = []
-elif NFLAG:
- # Note that it is on purpose that AFLAG and PFLAG are
- # tested dynamically each time through the loop
- prologue = [ \
- 'LINECOUNT = 0', \
- 'for FILE in ARGS:', \
- ' \tif FILE == \'-\':', \
- ' \t \tFP = sys.stdin', \
- ' \telse:', \
- ' \t \tFP = open(FILE, \'r\')', \
- ' \tLINENO = 0', \
- ' \twhile 1:', \
- ' \t \tLINE = FP.readline()', \
- ' \t \tif not LINE: break', \
- ' \t \tLINENO = LINENO + 1', \
- ' \t \tLINECOUNT = LINECOUNT + 1', \
- ' \t \tL = LINE[:-1]', \
- ' \t \taflag = AFLAG', \
- ' \t \tif aflag:', \
- ' \t \t \tif FS: F = string.splitfields(L, FS)', \
- ' \t \t \telse: F = string.split(L)' \
- ]
- epilogue = [ \
- ' \t \tif not PFLAG: continue', \
- ' \t \tif aflag:', \
- ' \t \t \tif FS: print string.joinfields(F, FS)', \
- ' \t \t \telse: print string.join(F)', \
- ' \t \telse: print L', \
- ]
-else:
- prologue = ['if 1:']
- epilogue = []
-
-# Note that we indent using tabs only, so that any indentation style
-# used in 'command' will come out right after re-indentation.
-
-program = string.joinfields(prologue, '\n') + '\n'
-for line in SCRIPT:
- program = program + (' \t \t' + line + '\n')
-program = program + (string.joinfields(epilogue, '\n') + '\n')
-
-import tempfile
-fp = tempfile.NamedTemporaryFile()
-fp.write(program)
-fp.flush()
-if DFLAG:
- import pdb
- pdb.run('execfile(' + `tfn` + ')')
-else:
- execfile(tfn)
diff --git a/Demo/scripts/primes.py b/Demo/scripts/primes.py
deleted file mode 100755
index 477c57bda9..0000000000
--- a/Demo/scripts/primes.py
+++ /dev/null
@@ -1,26 +0,0 @@
-#! /usr/bin/env python
-
-# Print prime numbers in a given range
-
-def main():
- import sys
- min, max = 2, 0x7fffffff
- if sys.argv[1:]:
- min = int(eval(sys.argv[1]))
- if sys.argv[2:]:
- max = int(eval(sys.argv[2]))
- primes(min, max)
-
-def primes(min, max):
- if 2 >= min: print 2
- primes = [2]
- i = 3
- while i <= max:
- for p in primes:
- if i%p == 0 or p*p > i: break
- if i%p <> 0:
- primes.append(i)
- if i >= min: print i
- i = i+2
-
-main()
diff --git a/Demo/scripts/queens.py b/Demo/scripts/queens.py
deleted file mode 100755
index 74756be7d8..0000000000
--- a/Demo/scripts/queens.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#! /usr/bin/env python
-
-"""N queens problem.
-
-The (well-known) problem is due to Niklaus Wirth.
-
-This solution is inspired by Dijkstra (Structured Programming). It is
-a classic recursive backtracking approach.
-
-"""
-
-N = 8 # Default; command line overrides
-
-class Queens:
-
- def __init__(self, n=N):
- self.n = n
- self.reset()
-
- def reset(self):
- n = self.n
- self.y = [None]*n # Where is the queen in column x
- self.row = [0]*n # Is row[y] safe?
- self.up = [0] * (2*n-1) # Is upward diagonal[x-y] safe?
- self.down = [0] * (2*n-1) # Is downward diagonal[x+y] safe?
- self.nfound = 0 # Instrumentation
-
- def solve(self, x=0): # Recursive solver
- for y in range(self.n):
- if self.safe(x, y):
- self.place(x, y)
- if x+1 == self.n:
- self.display()
- else:
- self.solve(x+1)
- self.remove(x, y)
-
- def safe(self, x, y):
- return not self.row[y] and not self.up[x-y] and not self.down[x+y]
-
- def place(self, x, y):
- self.y[x] = y
- self.row[y] = 1
- self.up[x-y] = 1
- self.down[x+y] = 1
-
- def remove(self, x, y):
- self.y[x] = None
- self.row[y] = 0
- self.up[x-y] = 0
- self.down[x+y] = 0
-
- silent = 0 # If set, count solutions only
-
- def display(self):
- self.nfound = self.nfound + 1
- if self.silent:
- return
- print '+-' + '--'*self.n + '+'
- for y in range(self.n-1, -1, -1):
- print '|',
- for x in range(self.n):
- if self.y[x] == y:
- print "Q",
- else:
- print ".",
- print '|'
- print '+-' + '--'*self.n + '+'
-
-def main():
- import sys
- silent = 0
- n = N
- if sys.argv[1:2] == ['-n']:
- silent = 1
- del sys.argv[1]
- if sys.argv[1:]:
- n = int(sys.argv[1])
- q = Queens(n)
- q.silent = silent
- q.solve()
- print "Found", q.nfound, "solutions."
-
-if __name__ == "__main__":
- main()
diff --git a/Demo/scripts/script.py b/Demo/scripts/script.py
deleted file mode 100755
index cbad3679d1..0000000000
--- a/Demo/scripts/script.py
+++ /dev/null
@@ -1,33 +0,0 @@
-#! /usr/bin/env python
-# script.py -- Make typescript of terminal session.
-# Usage:
-# -a Append to typescript.
-# -p Use Python as shell.
-# Author: Steen Lumholt.
-
-
-import os, time, sys
-import pty
-
-def read(fd):
- data = os.read(fd, 1024)
- file.write(data)
- return data
-
-shell = 'sh'
-filename = 'typescript'
-mode = 'w'
-if os.environ.has_key('SHELL'):
- shell = os.environ['SHELL']
-if '-a' in sys.argv:
- mode = 'a'
-if '-p' in sys.argv:
- shell = 'python'
-
-file = open(filename, mode)
-
-sys.stdout.write('Script started, file is %s\n' % filename)
-file.write('Script started on %s\n' % time.ctime(time.time()))
-pty.spawn(shell, read)
-file.write('Script done on %s\n' % time.ctime(time.time()))
-sys.stdout.write('Script done, file is %s\n' % filename)
diff --git a/Demo/scripts/unbirthday.py b/Demo/scripts/unbirthday.py
deleted file mode 100755
index e3b7be73f0..0000000000
--- a/Demo/scripts/unbirthday.py
+++ /dev/null
@@ -1,106 +0,0 @@
-#! /usr/bin/env python
-
-# Calculate your unbirthday count (see Alice in Wonderland).
-# This is defined as the number of days from your birth until today
-# that weren't your birthday. (The day you were born is not counted).
-# Leap years make it interesting.
-
-import sys
-import time
-import calendar
-
-def main():
- # Note that the range checks below also check for bad types,
- # e.g. 3.14 or (). However syntactically invalid replies
- # will raise an exception.
- if sys.argv[1:]:
- year = int(sys.argv[1])
- else:
- year = int(raw_input('In which year were you born? '))
- if 0<=year<100:
- print "I'll assume that by", year,
- year = year + 1900
- print 'you mean', year, 'and not the early Christian era'
- elif not (1850<=year<=2002):
- print "It's hard to believe you were born in", year
- return
- #
- if sys.argv[2:]:
- month = int(sys.argv[2])
- else:
- month = int(raw_input('And in which month? (1-12) '))
- if not (1<=month<=12):
- print 'There is no month numbered', month
- return
- #
- if sys.argv[3:]:
- day = int(sys.argv[3])
- else:
- day = int(raw_input('And on what day of that month? (1-31) '))
- if month == 2 and calendar.isleap(year):
- maxday = 29
- else:
- maxday = calendar.mdays[month]
- if not (1<=day<=maxday):
- print 'There are no', day, 'days in that month!'
- return
- #
- bdaytuple = (year, month, day)
- bdaydate = mkdate(bdaytuple)
- print 'You were born on', format(bdaytuple)
- #
- todaytuple = time.localtime()[:3]
- todaydate = mkdate(todaytuple)
- print 'Today is', format(todaytuple)
- #
- if bdaytuple > todaytuple:
- print 'You are a time traveler. Go back to the future!'
- return
- #
- if bdaytuple == todaytuple:
- print 'You were born today. Have a nice life!'
- return
- #
- days = todaydate - bdaydate
- print 'You have lived', days, 'days'
- #
- age = 0
- for y in range(year, todaytuple[0] + 1):
- if bdaytuple < (y, month, day) <= todaytuple:
- age = age + 1
- #
- print 'You are', age, 'years old'
- #
- if todaytuple[1:] == bdaytuple[1:]:
- print 'Congratulations! Today is your', nth(age), 'birthday'
- print 'Yesterday was your',
- else:
- print 'Today is your',
- print nth(days - age), 'unbirthday'
-
-def format((year, month, day)):
- return '%d %s %d' % (day, calendar.month_name[month], year)
-
-def nth(n):
- if n == 1: return '1st'
- if n == 2: return '2nd'
- if n == 3: return '3rd'
- return '%dth' % n
-
-def mkdate((year, month, day)):
- # Januari 1st, in 0 A.D. is arbitrarily defined to be day 1,
- # even though that day never actually existed and the calendar
- # was different then...
- days = year*365 # years, roughly
- days = days + (year+3)/4 # plus leap years, roughly
- days = days - (year+99)/100 # minus non-leap years every century
- days = days + (year+399)/400 # plus leap years every 4 centirues
- for i in range(1, month):
- if i == 2 and calendar.isleap(year):
- days = days + 29
- else:
- days = days + calendar.mdays[i]
- days = days + day
- return days
-
-main()
diff --git a/Demo/scripts/update.py b/Demo/scripts/update.py
deleted file mode 100755
index 2db65dcb29..0000000000
--- a/Demo/scripts/update.py
+++ /dev/null
@@ -1,91 +0,0 @@
-#! /usr/bin/env python
-
-# Update a bunch of files according to a script.
-# The input file contains lines of the form ::,
-# meaning that the given line of the given file is to be replaced
-# by the given text. This is useful for performing global substitutions
-# on grep output:
-
-import os
-import sys
-import regex
-
-pat = '^\([^: \t\n]+\):\([1-9][0-9]*\):'
-prog = regex.compile(pat)
-
-class FileObj:
- def __init__(self, filename):
- self.filename = filename
- self.changed = 0
- try:
- self.lines = open(filename, 'r').readlines()
- except IOError, msg:
- print '*** Can\'t open "%s":' % filename, msg
- self.lines = None
- return
- print 'diffing', self.filename
-
- def finish(self):
- if not self.changed:
- print 'no changes to', self.filename
- return
- try:
- os.rename(self.filename, self.filename + '~')
- fp = open(self.filename, 'w')
- except (os.error, IOError), msg:
- print '*** Can\'t rewrite "%s":' % self.filename, msg
- return
- print 'writing', self.filename
- for line in self.lines:
- fp.write(line)
- fp.close()
- self.changed = 0
-
- def process(self, lineno, rest):
- if self.lines is None:
- print '(not processed): %s:%s:%s' % (
- self.filename, lineno, rest),
- return
- i = eval(lineno) - 1
- if not 0 <= i < len(self.lines):
- print '*** Line number out of range: %s:%s:%s' % (
- self.filename, lineno, rest),
- return
- if self.lines[i] == rest:
- print '(no change): %s:%s:%s' % (
- self.filename, lineno, rest),
- return
- if not self.changed:
- self.changed = 1
- print '%sc%s' % (lineno, lineno)
- print '<', self.lines[i],
- print '---'
- self.lines[i] = rest
- print '>', self.lines[i],
-
-def main():
- if sys.argv[1:]:
- try:
- fp = open(sys.argv[1], 'r')
- except IOError, msg:
- print 'Can\'t open "%s":' % sys.argv[1], msg
- sys.exit(1)
- else:
- fp = sys.stdin
- curfile = None
- while 1:
- line = fp.readline()
- if not line:
- if curfile: curfile.finish()
- break
- n = prog.match(line)
- if n < 0:
- print 'Funny line:', line,
- continue
- filename, lineno = prog.group(1, 2)
- if not curfile or filename <> curfile.filename:
- if curfile: curfile.finish()
- curfile = FileObj(filename)
- curfile.process(lineno, line[n:])
-
-main()
diff --git a/Demo/scripts/wh.py b/Demo/scripts/wh.py
deleted file mode 100755
index b9b09efa6a..0000000000
--- a/Demo/scripts/wh.py
+++ /dev/null
@@ -1,2 +0,0 @@
-# This is here so I can use 'wh' instead of 'which' in '~/bin/generic_python'
-import which
diff --git a/Demo/sockets/README b/Demo/sockets/README
deleted file mode 100644
index 21ed808cc3..0000000000
--- a/Demo/sockets/README
+++ /dev/null
@@ -1,22 +0,0 @@
-This directory contains some demonstrations of the socket module:
-
-broadcast.py Broadcast the time to radio.py.
-echosvr.py About the simplest TCP server possible.
-finger.py Client for the 'finger' protocol.
-ftp.py A very simple ftp client.
-gopher.py A simple gopher client.
-radio.py Receive time broadcasts from broadcast.py.
-telnet.py Client for the 'telnet' protocol.
-throughput.py Client and server to measure TCP throughput.
-unixclient.py Unix socket example, client side
-unixserver.py Unix socket example, server side
-udpecho.py Client and server for the UDP echo protocol.
-
-The following file is only relevant on SGI machines (or other systems
-that support multicast):
-
-mcast.py A Python translation of
- /usr/people/4Dgifts/examples/network/mcast.c
- (Note that IN.py is in ../../lib/sgi.)
-
-See also ../../lib/nntp.py for another example of socket code.
diff --git a/Demo/sockets/broadcast.py b/Demo/sockets/broadcast.py
deleted file mode 100755
index a02b081a2e..0000000000
--- a/Demo/sockets/broadcast.py
+++ /dev/null
@@ -1,17 +0,0 @@
-# Send UDP broadcast packets
-
-MYPORT = 50000
-
-import sys, time
-from socket import *
-
-s = socket(AF_INET, SOCK_DGRAM)
-s.bind(('', 0))
-s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
-
-while 1:
- data = `time.time()` + '\n'
- s.sendto(data, ('', MYPORT))
- time.sleep(2)
-
-
diff --git a/Demo/sockets/echosvr.py b/Demo/sockets/echosvr.py
deleted file mode 100755
index a37f9c26eb..0000000000
--- a/Demo/sockets/echosvr.py
+++ /dev/null
@@ -1,31 +0,0 @@
-#! /usr/bin/env python
-
-# Python implementation of an 'echo' tcp server: echo all data it receives.
-#
-# This is the simplest possible server, servicing a single request only.
-
-import sys
-from socket import *
-
-# The standard echo port isn't very useful, it requires root permissions!
-# ECHO_PORT = 7
-ECHO_PORT = 50000 + 7
-BUFSIZE = 1024
-
-def main():
- if len(sys.argv) > 1:
- port = int(eval(sys.argv[1]))
- else:
- port = ECHO_PORT
- s = socket(AF_INET, SOCK_STREAM)
- s.bind(('', port))
- s.listen(1)
- conn, (remotehost, remoteport) = s.accept()
- print 'connected by', remotehost, remoteport
- while 1:
- data = conn.recv(BUFSIZE)
- if not data:
- break
- conn.send(data)
-
-main()
diff --git a/Demo/sockets/finger.py b/Demo/sockets/finger.py
deleted file mode 100755
index 0c2baed0b4..0000000000
--- a/Demo/sockets/finger.py
+++ /dev/null
@@ -1,58 +0,0 @@
-#! /usr/bin/env python
-
-# Python interface to the Internet finger daemon.
-#
-# Usage: finger [options] [user][@host] ...
-#
-# If no host is given, the finger daemon on the local host is contacted.
-# Options are passed uninterpreted to the finger daemon!
-
-
-import sys, string
-from socket import *
-
-
-# Hardcode the number of the finger port here.
-# It's not likely to change soon...
-#
-FINGER_PORT = 79
-
-
-# Function to do one remote finger invocation.
-# Output goes directly to stdout (although this can be changed).
-#
-def finger(host, args):
- s = socket(AF_INET, SOCK_STREAM)
- s.connect((host, FINGER_PORT))
- s.send(args + '\n')
- while 1:
- buf = s.recv(1024)
- if not buf: break
- sys.stdout.write(buf)
- sys.stdout.flush()
-
-
-# Main function: argument parsing.
-#
-def main():
- options = ''
- i = 1
- while i < len(sys.argv) and sys.argv[i][:1] == '-':
- options = options + sys.argv[i] + ' '
- i = i+1
- args = sys.argv[i:]
- if not args:
- args = ['']
- for arg in args:
- if '@' in arg:
- at = string.index(arg, '@')
- host = arg[at+1:]
- arg = arg[:at]
- else:
- host = ''
- finger(host, options + arg)
-
-
-# Call the main function.
-#
-main()
diff --git a/Demo/sockets/ftp.py b/Demo/sockets/ftp.py
deleted file mode 100755
index 8260c52f9c..0000000000
--- a/Demo/sockets/ftp.py
+++ /dev/null
@@ -1,146 +0,0 @@
-# A simple FTP client.
-#
-# The information to write this program was gathered from RFC 959,
-# but this is not a complete implementation! Yet it shows how a simple
-# FTP client can be built, and you are welcome to extend it to suit
-# it to your needs...
-#
-# How it works (assuming you've read the RFC):
-#
-# User commands are passed uninterpreted to the server. However, the
-# user never needs to send a PORT command. Rather, the client opens a
-# port right away and sends the appropriate PORT command to the server.
-# When a response code 150 is received, this port is used to receive
-# the data (which is written to stdout in this version), and when the
-# data is exhausted, a new port is opened and a corresponding PORT
-# command sent. In order to avoid errors when reusing ports quickly
-# (and because there is no s.getsockname() method in Python yet) we
-# cycle through a number of ports in the 50000 range.
-
-
-import sys, posix, string
-from socket import *
-
-
-BUFSIZE = 1024
-
-# Default port numbers used by the FTP protocol.
-#
-FTP_PORT = 21
-FTP_DATA_PORT = FTP_PORT - 1
-
-# Change the data port to something not needing root permissions.
-#
-FTP_DATA_PORT = FTP_DATA_PORT + 50000
-
-
-# Main program (called at the end of this file).
-#
-def main():
- hostname = sys.argv[1]
- control(hostname)
-
-
-# Control process (user interface and user protocol interpreter).
-#
-def control(hostname):
- #
- # Create control connection
- #
- s = socket(AF_INET, SOCK_STREAM)
- s.connect((hostname, FTP_PORT))
- f = s.makefile('r') # Reading the replies is easier from a file...
- #
- # Control loop
- #
- r = None
- while 1:
- code = getreply(f)
- if code in ('221', 'EOF'): break
- if code == '150':
- getdata(r)
- code = getreply(f)
- r = None
- if not r:
- r = newdataport(s, f)
- cmd = getcommand()
- if not cmd: break
- s.send(cmd + '\r\n')
-
-
-# Create a new data port and send a PORT command to the server for it.
-# (Cycle through a number of ports to avoid problems with reusing
-# a port within a short time.)
-#
-nextport = 0
-#
-def newdataport(s, f):
- global nextport
- port = nextport + FTP_DATA_PORT
- nextport = (nextport+1) % 16
- r = socket(AF_INET, SOCK_STREAM)
- r.bind((gethostbyname(gethostname()), port))
- r.listen(1)
- sendportcmd(s, f, port)
- return r
-
-
-# Send an appropriate port command.
-#
-def sendportcmd(s, f, port):
- hostname = gethostname()
- hostaddr = gethostbyname(hostname)
- hbytes = string.splitfields(hostaddr, '.')
- pbytes = [`port/256`, `port%256`]
- bytes = hbytes + pbytes
- cmd = 'PORT ' + string.joinfields(bytes, ',')
- s.send(cmd + '\r\n')
- code = getreply(f)
-
-
-# Process an ftp reply and return the 3-digit reply code (as a string).
-# The reply should be a line of text starting with a 3-digit number.
-# If the 4th char is '-', it is a multi-line reply and is
-# terminate by a line starting with the same 3-digit number.
-# Any text while receiving the reply is echoed to the file.
-#
-def getreply(f):
- line = f.readline()
- if not line: return 'EOF'
- print line,
- code = line[:3]
- if line[3:4] == '-':
- while 1:
- line = f.readline()
- if not line: break # Really an error
- print line,
- if line[:3] == code and line[3:4] != '-': break
- return code
-
-
-# Get the data from the data connection.
-#
-def getdata(r):
- print '(accepting data connection)'
- conn, host = r.accept()
- print '(data connection accepted)'
- while 1:
- data = conn.recv(BUFSIZE)
- if not data: break
- sys.stdout.write(data)
- print '(end of data connection)'
-
-# Get a command from the user.
-#
-def getcommand():
- try:
- while 1:
- line = raw_input('ftp.py> ')
- if line: return line
- except EOFError:
- return ''
-
-
-# Call the main program.
-#
-main()
diff --git a/Demo/sockets/gopher.py b/Demo/sockets/gopher.py
deleted file mode 100755
index a2ab3a2f6c..0000000000
--- a/Demo/sockets/gopher.py
+++ /dev/null
@@ -1,347 +0,0 @@
-#! /usr/bin/env python
-
-# A simple gopher client.
-#
-# Usage: gopher [ [selector] host [port] ]
-
-import string
-import sys
-import os
-import socket
-
-# Default selector, host and port
-DEF_SELECTOR = ''
-DEF_HOST = 'gopher.micro.umn.edu'
-DEF_PORT = 70
-
-# Recognized file types
-T_TEXTFILE = '0'
-T_MENU = '1'
-T_CSO = '2'
-T_ERROR = '3'
-T_BINHEX = '4'
-T_DOS = '5'
-T_UUENCODE = '6'
-T_SEARCH = '7'
-T_TELNET = '8'
-T_BINARY = '9'
-T_REDUNDANT = '+'
-T_SOUND = 's'
-
-# Dictionary mapping types to strings
-typename = {'0': '', '1': '', '2': '', '3': '', \
- '4': '', '5': '', '6': '', '7': '', \
- '8': '', '9': '', '+': '', 's': ''}
-
-# Oft-used characters and strings
-CRLF = '\r\n'
-TAB = '\t'
-
-# Open a TCP connection to a given host and port
-def open_socket(host, port):
- if not port:
- port = DEF_PORT
- elif type(port) == type(''):
- port = string.atoi(port)
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.connect((host, port))
- return s
-
-# Send a selector to a given host and port, return a file with the reply
-def send_request(selector, host, port):
- s = open_socket(host, port)
- s.send(selector + CRLF)
- s.shutdown(1)
- return s.makefile('r')
-
-# Get a menu in the form of a list of entries
-def get_menu(selector, host, port):
- f = send_request(selector, host, port)
- list = []
- while 1:
- line = f.readline()
- if not line:
- print '(Unexpected EOF from server)'
- break
- if line[-2:] == CRLF:
- line = line[:-2]
- elif line[-1:] in CRLF:
- line = line[:-1]
- if line == '.':
- break
- if not line:
- print '(Empty line from server)'
- continue
- typechar = line[0]
- parts = string.splitfields(line[1:], TAB)
- if len(parts) < 4:
- print '(Bad line from server:', `line`, ')'
- continue
- if len(parts) > 4:
- print '(Extra info from server:', parts[4:], ')'
- parts.insert(0, typechar)
- list.append(parts)
- f.close()
- return list
-
-# Get a text file as a list of lines, with trailing CRLF stripped
-def get_textfile(selector, host, port):
- list = []
- get_alt_textfile(selector, host, port, list.append)
- return list
-
-# Get a text file and pass each line to a function, with trailing CRLF stripped
-def get_alt_textfile(selector, host, port, func):
- f = send_request(selector, host, port)
- while 1:
- line = f.readline()
- if not line:
- print '(Unexpected EOF from server)'
- break
- if line[-2:] == CRLF:
- line = line[:-2]
- elif line[-1:] in CRLF:
- line = line[:-1]
- if line == '.':
- break
- if line[:2] == '..':
- line = line[1:]
- func(line)
- f.close()
-
-# Get a binary file as one solid data block
-def get_binary(selector, host, port):
- f = send_request(selector, host, port)
- data = f.read()
- f.close()
- return data
-
-# Get a binary file and pass each block to a function
-def get_alt_binary(selector, host, port, func, blocksize):
- f = send_request(selector, host, port)
- while 1:
- data = f.read(blocksize)
- if not data:
- break
- func(data)
-
-# A *very* simple interactive browser
-
-# Browser main command, has default arguments
-def browser(*args):
- selector = DEF_SELECTOR
- host = DEF_HOST
- port = DEF_PORT
- n = len(args)
- if n > 0 and args[0]:
- selector = args[0]
- if n > 1 and args[1]:
- host = args[1]
- if n > 2 and args[2]:
- port = args[2]
- if n > 3:
- raise RuntimeError, 'too many args'
- try:
- browse_menu(selector, host, port)
- except socket.error, msg:
- print 'Socket error:', msg
- sys.exit(1)
- except KeyboardInterrupt:
- print '\n[Goodbye]'
-
-# Browse a menu
-def browse_menu(selector, host, port):
- list = get_menu(selector, host, port)
- while 1:
- print '----- MENU -----'
- print 'Selector:', `selector`
- print 'Host:', host, ' Port:', port
- print
- for i in range(len(list)):
- item = list[i]
- typechar, description = item[0], item[1]
- print string.rjust(`i+1`, 3) + ':', description,
- if typename.has_key(typechar):
- print typename[typechar]
- else:
- print ''
- print
- while 1:
- try:
- str = raw_input('Choice [CR == up a level]: ')
- except EOFError:
- print
- return
- if not str:
- return
- try:
- choice = string.atoi(str)
- except string.atoi_error:
- print 'Choice must be a number; try again:'
- continue
- if not 0 < choice <= len(list):
- print 'Choice out of range; try again:'
- continue
- break
- item = list[choice-1]
- typechar = item[0]
- [i_selector, i_host, i_port] = item[2:5]
- if typebrowser.has_key(typechar):
- browserfunc = typebrowser[typechar]
- try:
- browserfunc(i_selector, i_host, i_port)
- except (IOError, socket.error):
- print '***', sys.exc_type, ':', sys.exc_value
- else:
- print 'Unsupported object type'
-
-# Browse a text file
-def browse_textfile(selector, host, port):
- x = None
- try:
- p = os.popen('${PAGER-more}', 'w')
- x = SaveLines(p)
- get_alt_textfile(selector, host, port, x.writeln)
- except IOError, msg:
- print 'IOError:', msg
- if x:
- x.close()
- f = open_savefile()
- if not f:
- return
- x = SaveLines(f)
- try:
- get_alt_textfile(selector, host, port, x.writeln)
- print 'Done.'
- except IOError, msg:
- print 'IOError:', msg
- x.close()
-
-# Browse a search index
-def browse_search(selector, host, port):
- while 1:
- print '----- SEARCH -----'
- print 'Selector:', `selector`
- print 'Host:', host, ' Port:', port
- print
- try:
- query = raw_input('Query [CR == up a level]: ')
- except EOFError:
- print
- break
- query = string.strip(query)
- if not query:
- break
- if '\t' in query:
- print 'Sorry, queries cannot contain tabs'
- continue
- browse_menu(selector + TAB + query, host, port)
-
-# "Browse" telnet-based information, i.e. open a telnet session
-def browse_telnet(selector, host, port):
- if selector:
- print 'Log in as', `selector`
- if type(port) <> type(''):
- port = `port`
- sts = os.system('set -x; exec telnet ' + host + ' ' + port)
- if sts:
- print 'Exit status:', sts
-
-# "Browse" a binary file, i.e. save it to a file
-def browse_binary(selector, host, port):
- f = open_savefile()
- if not f:
- return
- x = SaveWithProgress(f)
- get_alt_binary(selector, host, port, x.write, 8*1024)
- x.close()
-
-# "Browse" a sound file, i.e. play it or save it
-def browse_sound(selector, host, port):
- browse_binary(selector, host, port)
-
-# Dictionary mapping types to browser functions
-typebrowser = {'0': browse_textfile, '1': browse_menu, \
- '4': browse_binary, '5': browse_binary, '6': browse_textfile, \
- '7': browse_search, \
- '8': browse_telnet, '9': browse_binary, 's': browse_sound}
-
-# Class used to save lines, appending a newline to each line
-class SaveLines:
- def __init__(self, f):
- self.f = f
- def writeln(self, line):
- self.f.write(line + '\n')
- def close(self):
- sts = self.f.close()
- if sts:
- print 'Exit status:', sts
-
-# Class used to save data while showing progress
-class SaveWithProgress:
- def __init__(self, f):
- self.f = f
- def write(self, data):
- sys.stdout.write('#')
- sys.stdout.flush()
- self.f.write(data)
- def close(self):
- print
- sts = self.f.close()
- if sts:
- print 'Exit status:', sts
-
-# Ask for and open a save file, or return None if not to save
-def open_savefile():
- try:
- savefile = raw_input( \
- 'Save as file [CR == don\'t save; |pipeline or ~user/... OK]: ')
- except EOFError:
- print
- return None
- savefile = string.strip(savefile)
- if not savefile:
- return None
- if savefile[0] == '|':
- cmd = string.strip(savefile[1:])
- try:
- p = os.popen(cmd, 'w')
- except IOError, msg:
- print `cmd`, ':', msg
- return None
- print 'Piping through', `cmd`, '...'
- return p
- if savefile[0] == '~':
- savefile = os.path.expanduser(savefile)
- try:
- f = open(savefile, 'w')
- except IOError, msg:
- print `savefile`, ':', msg
- return None
- print 'Saving to', `savefile`, '...'
- return f
-
-# Test program
-def test():
- if sys.argv[4:]:
- print 'usage: gopher [ [selector] host [port] ]'
- sys.exit(2)
- elif sys.argv[3:]:
- browser(sys.argv[1], sys.argv[2], sys.argv[3])
- elif sys.argv[2:]:
- try:
- port = string.atoi(sys.argv[2])
- selector = ''
- host = sys.argv[1]
- except string.atoi_error:
- selector = sys.argv[1]
- host = sys.argv[2]
- port = ''
- browser(selector, host, port)
- elif sys.argv[1:]:
- browser('', sys.argv[1])
- else:
- browser()
-
-# Call the test program as a main program
-test()
diff --git a/Demo/sockets/mcast.py b/Demo/sockets/mcast.py
deleted file mode 100755
index cc7a7e07d4..0000000000
--- a/Demo/sockets/mcast.py
+++ /dev/null
@@ -1,94 +0,0 @@
-# Send/receive UDP multicast packets.
-# Requires that your OS kernel supports IP multicast.
-# This is built-in on SGI, still optional for most other vendors.
-#
-# Usage:
-# mcast -s (sender)
-# mcast -b (sender, using broadcast instead multicast)
-# mcast (receivers)
-
-MYPORT = 8123
-MYGROUP = '225.0.0.250'
-
-import sys
-import time
-import struct
-import regsub
-from socket import *
-
-
-# Main program
-def main():
- flags = sys.argv[1:]
- #
- if flags:
- sender(flags[0])
- else:
- receiver()
-
-
-# Sender subroutine (only one per local area network)
-def sender(flag):
- s = socket(AF_INET, SOCK_DGRAM)
- if flag == '-b':
- s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
- mygroup = ''
- else:
- mygroup = MYGROUP
- ttl = struct.pack('b', 1) # Time-to-live
- s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl)
- while 1:
- data = `time.time()`
-## data = data + (1400 - len(data)) * '\0'
- s.sendto(data, (mygroup, MYPORT))
- time.sleep(1)
-
-
-# Receiver subroutine (as many as you like)
-def receiver():
- # Open and initialize the socket
- s = openmcastsock(MYGROUP, MYPORT)
- #
- # Loop, printing any data we receive
- while 1:
- data, sender = s.recvfrom(1500)
- while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's
- print sender, ':', `data`
-
-
-# Open a UDP socket, bind it to a port and select a multicast group
-def openmcastsock(group, port):
- # Import modules used only here
- import string
- import struct
- #
- # Create a socket
- s = socket(AF_INET, SOCK_DGRAM)
- #
- # Allow multiple copies of this program on one machine
- # (not strictly needed)
- s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
- #
- # Bind it to the port
- s.bind(('', port))
- #
- # Look up multicast group address in name server
- # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format)
- group = gethostbyname(group)
- #
- # Construct binary group address
- bytes = map(int, string.split(group, "."))
- grpaddr = 0
- for byte in bytes: grpaddr = (grpaddr << 8) | byte
- #
- # Construct struct mreq from grpaddr and ifaddr
- ifaddr = INADDR_ANY
- mreq = struct.pack('ll', htonl(grpaddr), htonl(ifaddr))
- #
- # Add group membership
- s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)
- #
- return s
-
-
-main()
diff --git a/Demo/sockets/radio.py b/Demo/sockets/radio.py
deleted file mode 100755
index 6131d40053..0000000000
--- a/Demo/sockets/radio.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# Receive UDP packets transmitted by a broadcasting service
-
-MYPORT = 50000
-
-import sys
-from socket import *
-
-s = socket(AF_INET, SOCK_DGRAM)
-s.bind(('', MYPORT))
-
-while 1:
- data, wherefrom = s.recvfrom(1500, 0)
- sys.stderr.write(`wherefrom` + '\n')
- sys.stdout.write(data)
diff --git a/Demo/sockets/rpython.py b/Demo/sockets/rpython.py
deleted file mode 100755
index 77b2a7a516..0000000000
--- a/Demo/sockets/rpython.py
+++ /dev/null
@@ -1,35 +0,0 @@
-#! /usr/bin/env python
-
-# Remote python client.
-# Execute Python commands remotely and send output back.
-
-import sys
-import string
-from socket import *
-
-PORT = 4127
-BUFSIZE = 1024
-
-def main():
- if len(sys.argv) < 3:
- print "usage: rpython host command"
- sys.exit(2)
- host = sys.argv[1]
- port = PORT
- i = string.find(host, ':')
- if i >= 0:
- port = string.atoi(port[i+1:])
- host = host[:i]
- command = string.join(sys.argv[2:])
- s = socket(AF_INET, SOCK_STREAM)
- s.connect((host, port))
- s.send(command)
- s.shutdown(1)
- reply = ''
- while 1:
- data = s.recv(BUFSIZE)
- if not data: break
- reply = reply + data
- print reply,
-
-main()
diff --git a/Demo/sockets/rpythond.py b/Demo/sockets/rpythond.py
deleted file mode 100755
index 1109a99e18..0000000000
--- a/Demo/sockets/rpythond.py
+++ /dev/null
@@ -1,52 +0,0 @@
-#! /usr/bin/env python
-
-# Remote python server.
-# Execute Python commands remotely and send output back.
-# WARNING: This version has a gaping security hole -- it accepts requests
-# from any host on the Internet!
-
-import sys
-from socket import *
-import StringIO
-import traceback
-
-PORT = 4127
-BUFSIZE = 1024
-
-def main():
- if len(sys.argv) > 1:
- port = int(eval(sys.argv[1]))
- else:
- port = PORT
- s = socket(AF_INET, SOCK_STREAM)
- s.bind(('', port))
- s.listen(1)
- while 1:
- conn, (remotehost, remoteport) = s.accept()
- print 'connected by', remotehost, remoteport
- request = ''
- while 1:
- data = conn.recv(BUFSIZE)
- if not data:
- break
- request = request + data
- reply = execute(request)
- conn.send(reply)
- conn.close()
-
-def execute(request):
- stdout = sys.stdout
- stderr = sys.stderr
- sys.stdout = sys.stderr = fakefile = StringIO.StringIO()
- try:
- try:
- exec request in {}, {}
- except:
- print
- traceback.print_exc(100)
- finally:
- sys.stderr = stderr
- sys.stdout = stdout
- return fakefile.getvalue()
-
-main()
diff --git a/Demo/sockets/telnet.py b/Demo/sockets/telnet.py
deleted file mode 100755
index ee7c43b874..0000000000
--- a/Demo/sockets/telnet.py
+++ /dev/null
@@ -1,109 +0,0 @@
-#! /usr/bin/env python
-
-# Minimal interface to the Internet telnet protocol.
-#
-# It refuses all telnet options and does not recognize any of the other
-# telnet commands, but can still be used to connect in line-by-line mode.
-# It's also useful to play with a number of other services,
-# like time, finger, smtp and even ftp.
-#
-# Usage: telnet host [port]
-#
-# The port may be a service name or a decimal port number;
-# it defaults to 'telnet'.
-
-
-import sys, posix, time
-from socket import *
-
-BUFSIZE = 1024
-
-# Telnet protocol characters
-
-IAC = chr(255) # Interpret as command
-DONT = chr(254)
-DO = chr(253)
-WONT = chr(252)
-WILL = chr(251)
-
-def main():
- host = sys.argv[1]
- try:
- hostaddr = gethostbyname(host)
- except error:
- sys.stderr.write(sys.argv[1] + ': bad host name\n')
- sys.exit(2)
- #
- if len(sys.argv) > 2:
- servname = sys.argv[2]
- else:
- servname = 'telnet'
- #
- if '0' <= servname[:1] <= '9':
- port = eval(servname)
- else:
- try:
- port = getservbyname(servname, 'tcp')
- except error:
- sys.stderr.write(servname + ': bad tcp service name\n')
- sys.exit(2)
- #
- s = socket(AF_INET, SOCK_STREAM)
- #
- try:
- s.connect((host, port))
- except error, msg:
- sys.stderr.write('connect failed: ' + `msg` + '\n')
- sys.exit(1)
- #
- pid = posix.fork()
- #
- if pid == 0:
- # child -- read stdin, write socket
- while 1:
- line = sys.stdin.readline()
- s.send(line)
- else:
- # parent -- read socket, write stdout
- iac = 0 # Interpret next char as command
- opt = '' # Interpret next char as option
- while 1:
- data = s.recv(BUFSIZE)
- if not data:
- # EOF; kill child and exit
- sys.stderr.write( '(Closed by remote host)\n')
- posix.kill(pid, 9)
- sys.exit(1)
- cleandata = ''
- for c in data:
- if opt:
- print ord(c)
- s.send(opt + c)
- opt = ''
- elif iac:
- iac = 0
- if c == IAC:
- cleandata = cleandata + c
- elif c in (DO, DONT):
- if c == DO: print '(DO)',
- else: print '(DONT)',
- opt = IAC + WONT
- elif c in (WILL, WONT):
- if c == WILL: print '(WILL)',
- else: print '(WONT)',
- opt = IAC + DONT
- else:
- print '(command)', ord(c)
- elif c == IAC:
- iac = 1
- print '(IAC)',
- else:
- cleandata = cleandata + c
- sys.stdout.write(cleandata)
- sys.stdout.flush()
-
-
-try:
- main()
-except KeyboardInterrupt:
- pass
diff --git a/Demo/sockets/throughput.py b/Demo/sockets/throughput.py
deleted file mode 100755
index fa250e7755..0000000000
--- a/Demo/sockets/throughput.py
+++ /dev/null
@@ -1,93 +0,0 @@
-#! /usr/bin/env python
-
-# Test network throughput.
-#
-# Usage:
-# 1) on host_A: throughput -s [port] # start a server
-# 2) on host_B: throughput -c count host_A [port] # start a client
-#
-# The server will service multiple clients until it is killed.
-#
-# The client performs one transfer of count*BUFSIZE bytes and
-# measures the time it takes (roundtrip!).
-
-
-import sys, time
-from socket import *
-
-MY_PORT = 50000 + 42
-
-BUFSIZE = 1024
-
-
-def main():
- if len(sys.argv) < 2:
- usage()
- if sys.argv[1] == '-s':
- server()
- elif sys.argv[1] == '-c':
- client()
- else:
- usage()
-
-
-def usage():
- sys.stdout = sys.stderr
- print 'Usage: (on host_A) throughput -s [port]'
- print 'and then: (on host_B) throughput -c count host_A [port]'
- sys.exit(2)
-
-
-def server():
- if len(sys.argv) > 2:
- port = eval(sys.argv[2])
- else:
- port = MY_PORT
- s = socket(AF_INET, SOCK_STREAM)
- s.bind(('', port))
- s.listen(1)
- print 'Server ready...'
- while 1:
- conn, (host, remoteport) = s.accept()
- while 1:
- data = conn.recv(BUFSIZE)
- if not data:
- break
- del data
- conn.send('OK\n')
- conn.close()
- print 'Done with', host, 'port', remoteport
-
-
-def client():
- if len(sys.argv) < 4:
- usage()
- count = int(eval(sys.argv[2]))
- host = sys.argv[3]
- if len(sys.argv) > 4:
- port = eval(sys.argv[4])
- else:
- port = MY_PORT
- testdata = 'x' * (BUFSIZE-1) + '\n'
- t1 = time.time()
- s = socket(AF_INET, SOCK_STREAM)
- t2 = time.time()
- s.connect((host, port))
- t3 = time.time()
- i = 0
- while i < count:
- i = i+1
- s.send(testdata)
- s.shutdown(1) # Send EOF
- t4 = time.time()
- data = s.recv(BUFSIZE)
- t5 = time.time()
- print data
- print 'Raw timers:', t1, t2, t3, t4, t5
- print 'Intervals:', t2-t1, t3-t2, t4-t3, t5-t4
- print 'Total:', t5-t1
- print 'Throughput:', round((BUFSIZE*count*0.001) / (t5-t1), 3),
- print 'K/sec.'
-
-
-main()
diff --git a/Demo/sockets/udpecho.py b/Demo/sockets/udpecho.py
deleted file mode 100755
index 4410165e3a..0000000000
--- a/Demo/sockets/udpecho.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#! /usr/bin/env python
-
-# Client and server for udp (datagram) echo.
-#
-# Usage: udpecho -s [port] (to start a server)
-# or: udpecho -c host [port] 2:
- port = eval(sys.argv[2])
- else:
- port = ECHO_PORT
- s = socket(AF_INET, SOCK_DGRAM)
- s.bind(('', port))
- print 'udp echo server ready'
- while 1:
- data, addr = s.recvfrom(BUFSIZE)
- print 'server received', `data`, 'from', `addr`
- s.sendto(data, addr)
-
-def client():
- if len(sys.argv) < 3:
- usage()
- host = sys.argv[2]
- if len(sys.argv) > 3:
- port = eval(sys.argv[3])
- else:
- port = ECHO_PORT
- addr = host, port
- s = socket(AF_INET, SOCK_DGRAM)
- s.bind(('', 0))
- print 'udp echo client ready, reading stdin'
- while 1:
- line = sys.stdin.readline()
- if not line:
- break
- s.sendto(line, addr)
- data, fromaddr = s.recvfrom(BUFSIZE)
- print 'client received', `data`, 'from', `fromaddr`
-
-main()
diff --git a/Demo/sockets/unicast.py b/Demo/sockets/unicast.py
deleted file mode 100644
index 1e9caebd2a..0000000000
--- a/Demo/sockets/unicast.py
+++ /dev/null
@@ -1,16 +0,0 @@
-# Send UDP broadcast packets
-
-MYPORT = 50000
-
-import sys, time
-from socket import *
-
-s = socket(AF_INET, SOCK_DGRAM)
-s.bind(('', 0))
-
-while 1:
- data = `time.time()` + '\n'
- s.sendto(data, ('', MYPORT))
- time.sleep(2)
-
-
diff --git a/Demo/sockets/unixclient.py b/Demo/sockets/unixclient.py
deleted file mode 100644
index a0d80f6083..0000000000
--- a/Demo/sockets/unixclient.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# Echo client demo using Unix sockets
-# Piet van Oostrum
-from socket import *
-FILE = 'blabla'
-s = socket(AF_UNIX, SOCK_STREAM)
-s.connect(FILE)
-s.send('Hello, world')
-data = s.recv(1024)
-s.close()
-print 'Received', `data`
diff --git a/Demo/sockets/unixserver.py b/Demo/sockets/unixserver.py
deleted file mode 100644
index d4c706188f..0000000000
--- a/Demo/sockets/unixserver.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# Echo server demo using Unix sockets (handles one connection only)
-# Piet van Oostrum
-from socket import *
-FILE = 'blabla'
-s = socket(AF_UNIX, SOCK_STREAM)
-s.bind(FILE)
-print 'Sock name is: ['+s.getsockname()+']'
-s.listen(1)
-conn, addr = s.accept()
-print 'Connected by', addr
-while 1:
- data = conn.recv(1024)
- if not data: break
- conn.send(data)
-conn.close()
diff --git a/Demo/threads/Coroutine.py b/Demo/threads/Coroutine.py
deleted file mode 100644
index 0cf9255362..0000000000
--- a/Demo/threads/Coroutine.py
+++ /dev/null
@@ -1,160 +0,0 @@
-# Coroutine implementation using Python threads.
-#
-# Combines ideas from Guido's Generator module, and from the coroutine
-# features of Icon and Simula 67.
-#
-# To run a collection of functions as coroutines, you need to create
-# a Coroutine object to control them:
-# co = Coroutine()
-# and then 'create' a subsidiary object for each function in the
-# collection:
-# cof1 = co.create(f1 [, arg1, arg2, ...]) # [] means optional,
-# cof2 = co.create(f2 [, arg1, arg2, ...]) #... not list
-# cof3 = co.create(f3 [, arg1, arg2, ...])
-# etc. The functions need not be distinct; 'create'ing the same
-# function multiple times gives you independent instances of the
-# function.
-#
-# To start the coroutines running, use co.tran on one of the create'd
-# functions; e.g., co.tran(cof2). The routine that first executes
-# co.tran is called the "main coroutine". It's special in several
-# respects: it existed before you created the Coroutine object; if any of
-# the create'd coroutines exits (does a return, or suffers an unhandled
-# exception), EarlyExit error is raised in the main coroutine; and the
-# co.detach() method transfers control directly to the main coroutine
-# (you can't use co.tran() for this because the main coroutine doesn't
-# have a name ...).
-#
-# Coroutine objects support these methods:
-#
-# handle = .create(func [, arg1, arg2, ...])
-# Creates a coroutine for an invocation of func(arg1, arg2, ...),
-# and returns a handle ("name") for the coroutine so created. The
-# handle can be used as the target in a subsequent .tran().
-#
-# .tran(target, data=None)
-# Transfer control to the create'd coroutine "target", optionally
-# passing it an arbitrary piece of data. To the coroutine A that does
-# the .tran, .tran acts like an ordinary function call: another
-# coroutine B can .tran back to it later, and if it does A's .tran
-# returns the 'data' argument passed to B's tran. E.g.,
-#
-# in coroutine coA in coroutine coC in coroutine coB
-# x = co.tran(coC) co.tran(coB) co.tran(coA,12)
-# print x # 12
-#
-# The data-passing feature is taken from Icon, and greatly cuts
-# the need to use global variables for inter-coroutine communication.
-#
-# .back( data=None )
-# The same as .tran(invoker, data=None), where 'invoker' is the
-# coroutine that most recently .tran'ed control to the coroutine
-# doing the .back. This is akin to Icon's "&source".
-#
-# .detach( data=None )
-# The same as .tran(main, data=None), where 'main' is the
-# (unnameable!) coroutine that started it all. 'main' has all the
-# rights of any other coroutine: upon receiving control, it can
-# .tran to an arbitrary coroutine of its choosing, go .back to
-# the .detach'er, or .kill the whole thing.
-#
-# .kill()
-# Destroy all the coroutines, and return control to the main
-# coroutine. None of the create'ed coroutines can be resumed after a
-# .kill(). An EarlyExit exception does a .kill() automatically. It's
-# a good idea to .kill() coroutines you're done with, since the
-# current implementation consumes a thread for each coroutine that
-# may be resumed.
-
-import thread
-import sync
-
-class _CoEvent:
- def __init__(self, func):
- self.f = func
- self.e = sync.event()
-
- def __repr__(self):
- if self.f is None:
- return 'main coroutine'
- else:
- return 'coroutine for func ' + self.f.func_name
-
- def __hash__(self):
- return id(self)
-
- def __cmp__(x,y):
- return cmp(id(x), id(y))
-
- def resume(self):
- self.e.post()
-
- def wait(self):
- self.e.wait()
- self.e.clear()
-
-Killed = 'Coroutine.Killed'
-EarlyExit = 'Coroutine.EarlyExit'
-
-class Coroutine:
- def __init__(self):
- self.active = self.main = _CoEvent(None)
- self.invokedby = {self.main: None}
- self.killed = 0
- self.value = None
- self.terminated_by = None
-
- def create(self, func, *args):
- me = _CoEvent(func)
- self.invokedby[me] = None
- thread.start_new_thread(self._start, (me,) + args)
- return me
-
- def _start(self, me, *args):
- me.wait()
- if not self.killed:
- try:
- try:
- apply(me.f, args)
- except Killed:
- pass
- finally:
- if not self.killed:
- self.terminated_by = me
- self.kill()
-
- def kill(self):
- if self.killed:
- raise TypeError, 'kill() called on dead coroutines'
- self.killed = 1
- for coroutine in self.invokedby.keys():
- coroutine.resume()
-
- def back(self, data=None):
- return self.tran( self.invokedby[self.active], data )
-
- def detach(self, data=None):
- return self.tran( self.main, data )
-
- def tran(self, target, data=None):
- if not self.invokedby.has_key(target):
- raise TypeError, '.tran target ' + `target` + \
- ' is not an active coroutine'
- if self.killed:
- raise TypeError, '.tran target ' + `target` + ' is killed'
- self.value = data
- me = self.active
- self.invokedby[target] = me
- self.active = target
- target.resume()
-
- me.wait()
- if self.killed:
- if self.main is not me:
- raise Killed
- if self.terminated_by is not None:
- raise EarlyExit, `self.terminated_by` + ' terminated early'
-
- return self.value
-
-# end of module
diff --git a/Demo/threads/Generator.py b/Demo/threads/Generator.py
deleted file mode 100644
index fbba06ad0b..0000000000
--- a/Demo/threads/Generator.py
+++ /dev/null
@@ -1,84 +0,0 @@
-# Generator implementation using threads
-
-import thread
-
-Killed = 'Generator.Killed'
-
-class Generator:
- # Constructor
- def __init__(self, func, args):
- self.getlock = thread.allocate_lock()
- self.putlock = thread.allocate_lock()
- self.getlock.acquire()
- self.putlock.acquire()
- self.func = func
- self.args = args
- self.done = 0
- self.killed = 0
- thread.start_new_thread(self._start, ())
- # Internal routine
- def _start(self):
- try:
- self.putlock.acquire()
- if not self.killed:
- try:
- apply(self.func, (self,) + self.args)
- except Killed:
- pass
- finally:
- if not self.killed:
- self.done = 1
- self.getlock.release()
- # Called by producer for each value; raise Killed if no more needed
- def put(self, value):
- if self.killed:
- raise TypeError, 'put() called on killed generator'
- self.value = value
- self.getlock.release() # Resume consumer thread
- self.putlock.acquire() # Wait for next get() call
- if self.killed:
- raise Killed
- # Called by producer to get next value; raise EOFError if no more
- def get(self):
- if self.killed:
- raise TypeError, 'get() called on killed generator'
- self.putlock.release() # Resume producer thread
- self.getlock.acquire() # Wait for value to appear
- if self.done:
- raise EOFError # Say there are no more values
- return self.value
- # Called by consumer if no more values wanted
- def kill(self):
- if self.killed:
- raise TypeError, 'kill() called on killed generator'
- self.killed = 1
- self.putlock.release()
- # Clone constructor
- def clone(self):
- return Generator(self.func, self.args)
-
-def pi(g):
- k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
- while 1:
- # Next approximation
- p, q, k = k*k, 2L*k+1L, k+1L
- a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
- # Print common digits
- d, d1 = a/b, a1/b1
- while d == d1:
- g.put(int(d))
- a, a1 = 10L*(a%b), 10L*(a1%b1)
- d, d1 = a/b, a1/b1
-
-def test():
- g = Generator(pi, ())
- g.kill()
- g = Generator(pi, ())
- for i in range(10): print g.get(),
- print
- h = g.clone()
- g.kill()
- while 1:
- print h.get(),
-
-test()
diff --git a/Demo/threads/README b/Demo/threads/README
deleted file mode 100644
index fee6aad326..0000000000
--- a/Demo/threads/README
+++ /dev/null
@@ -1,13 +0,0 @@
-This directory contains some demonstrations of the thread module.
-
-These are mostly "proof of concept" type applications:
-
-Generator.py Generator class implemented with threads.
-find.py Parallelized "find(1)" (looks for directories).
-sync.py Condition variables primitives by Tim Peters.
-telnet.py Version of ../sockets/telnet.py using threads.
-wpi.py Version of ../scripts/pi.py using threads (needs stdwin).
-
-Coroutine.py Coroutines using threads, by Tim Peters (22 May 94)
-fcmp.py Example of above, by Tim
-squasher.py Another example of above, also by Tim
diff --git a/Demo/threads/fcmp.py b/Demo/threads/fcmp.py
deleted file mode 100644
index 83ebe01103..0000000000
--- a/Demo/threads/fcmp.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# Coroutine example: controlling multiple instances of a single function
-
-from Coroutine import *
-
-# fringe visits a nested list in inorder, and detaches for each non-list
-# element; raises EarlyExit after the list is exhausted
-def fringe( co, list ):
- for x in list:
- if type(x) is type([]):
- fringe(co, x)
- else:
- co.back(x)
-
-def printinorder( list ):
- co = Coroutine()
- f = co.create(fringe, co, list)
- try:
- while 1:
- print co.tran(f),
- except EarlyExit:
- pass
- print
-
-printinorder([1,2,3]) # 1 2 3
-printinorder([[[[1,[2]]],3]]) # ditto
-x = [0, 1, [2, [3]], [4,5], [[[6]]] ]
-printinorder(x) # 0 1 2 3 4 5 6
-
-# fcmp lexicographically compares the fringes of two nested lists
-def fcmp( l1, l2 ):
- co1 = Coroutine(); f1 = co1.create(fringe, co1, l1)
- co2 = Coroutine(); f2 = co2.create(fringe, co2, l2)
- while 1:
- try:
- v1 = co1.tran(f1)
- except EarlyExit:
- try:
- v2 = co2.tran(f2)
- except EarlyExit:
- return 0
- co2.kill()
- return -1
- try:
- v2 = co2.tran(f2)
- except EarlyExit:
- co1.kill()
- return 1
- if v1 != v2:
- co1.kill(); co2.kill()
- return cmp(v1,v2)
-
-print fcmp(range(7), x) # 0; fringes are equal
-print fcmp(range(6), x) # -1; 1st list ends early
-print fcmp(x, range(6)) # 1; 2nd list ends early
-print fcmp(range(8), x) # 1; 2nd list ends early
-print fcmp(x, range(8)) # -1; 1st list ends early
-print fcmp([1,[[2],8]],
- [[[1],2],8]) # 0
-print fcmp([1,[[3],8]],
- [[[1],2],8]) # 1
-print fcmp([1,[[2],8]],
- [[[1],2],9]) # -1
-
-# end of example
diff --git a/Demo/threads/find.py b/Demo/threads/find.py
deleted file mode 100644
index ab581e3473..0000000000
--- a/Demo/threads/find.py
+++ /dev/null
@@ -1,155 +0,0 @@
-# A parallelized "find(1)" using the thread module.
-
-# This demonstrates the use of a work queue and worker threads.
-# It really does do more stats/sec when using multiple threads,
-# although the improvement is only about 20-30 percent.
-# (That was 8 years ago. In 2002, on Linux, I can't measure
-# a speedup. :-( )
-
-# I'm too lazy to write a command line parser for the full find(1)
-# command line syntax, so the predicate it searches for is wired-in,
-# see function selector() below. (It currently searches for files with
-# world write permission.)
-
-# Usage: parfind.py [-w nworkers] [directory] ...
-# Default nworkers is 4
-
-
-import sys
-import getopt
-import string
-import time
-import os
-from stat import *
-import thread
-
-
-# Work queue class. Usage:
-# wq = WorkQ()
-# wq.addwork(func, (arg1, arg2, ...)) # one or more calls
-# wq.run(nworkers)
-# The work is done when wq.run() completes.
-# The function calls executed by the workers may add more work.
-# Don't use keyboard interrupts!
-
-class WorkQ:
-
- # Invariants:
-
- # - busy and work are only modified when mutex is locked
- # - len(work) is the number of jobs ready to be taken
- # - busy is the number of jobs being done
- # - todo is locked iff there is no work and somebody is busy
-
- def __init__(self):
- self.mutex = thread.allocate()
- self.todo = thread.allocate()
- self.todo.acquire()
- self.work = []
- self.busy = 0
-
- def addwork(self, func, args):
- job = (func, args)
- self.mutex.acquire()
- self.work.append(job)
- self.mutex.release()
- if len(self.work) == 1:
- self.todo.release()
-
- def _getwork(self):
- self.todo.acquire()
- self.mutex.acquire()
- if self.busy == 0 and len(self.work) == 0:
- self.mutex.release()
- self.todo.release()
- return None
- job = self.work[0]
- del self.work[0]
- self.busy = self.busy + 1
- self.mutex.release()
- if len(self.work) > 0:
- self.todo.release()
- return job
-
- def _donework(self):
- self.mutex.acquire()
- self.busy = self.busy - 1
- if self.busy == 0 and len(self.work) == 0:
- self.todo.release()
- self.mutex.release()
-
- def _worker(self):
- time.sleep(0.00001) # Let other threads run
- while 1:
- job = self._getwork()
- if not job:
- break
- func, args = job
- apply(func, args)
- self._donework()
-
- def run(self, nworkers):
- if not self.work:
- return # Nothing to do
- for i in range(nworkers-1):
- thread.start_new(self._worker, ())
- self._worker()
- self.todo.acquire()
-
-
-# Main program
-
-def main():
- nworkers = 4
- opts, args = getopt.getopt(sys.argv[1:], '-w:')
- for opt, arg in opts:
- if opt == '-w':
- nworkers = string.atoi(arg)
- if not args:
- args = [os.curdir]
-
- wq = WorkQ()
- for dir in args:
- wq.addwork(find, (dir, selector, wq))
-
- t1 = time.time()
- wq.run(nworkers)
- t2 = time.time()
-
- sys.stderr.write('Total time ' + `t2-t1` + ' sec.\n')
-
-
-# The predicate -- defines what files we look for.
-# Feel free to change this to suit your purpose
-
-def selector(dir, name, fullname, stat):
- # Look for world writable files that are not symlinks
- return (stat[ST_MODE] & 0002) != 0 and not S_ISLNK(stat[ST_MODE])
-
-
-# The find procedure -- calls wq.addwork() for subdirectories
-
-def find(dir, pred, wq):
- try:
- names = os.listdir(dir)
- except os.error, msg:
- print `dir`, ':', msg
- return
- for name in names:
- if name not in (os.curdir, os.pardir):
- fullname = os.path.join(dir, name)
- try:
- stat = os.lstat(fullname)
- except os.error, msg:
- print `fullname`, ':', msg
- continue
- if pred(dir, name, fullname, stat):
- print fullname
- if S_ISDIR(stat[ST_MODE]):
- if not os.path.ismount(fullname):
- wq.addwork(find, (fullname, pred, wq))
-
-
-# Call the main program
-
-main()
diff --git a/Demo/threads/squasher.py b/Demo/threads/squasher.py
deleted file mode 100644
index 0d59cb839b..0000000000
--- a/Demo/threads/squasher.py
+++ /dev/null
@@ -1,105 +0,0 @@
-# Coroutine example: general coroutine transfers
-#
-# The program is a variation of a Simula 67 program due to Dahl & Hoare,
-# (Dahl/Dijkstra/Hoare, Structured Programming; Academic Press, 1972)
-# who in turn credit the original example to Conway.
-#
-# We have a number of input lines, terminated by a 0 byte. The problem
-# is to squash them together into output lines containing 72 characters
-# each. A semicolon must be added between input lines. Runs of blanks
-# and tabs in input lines must be squashed into single blanks.
-# Occurrences of "**" in input lines must be replaced by "^".
-#
-# Here's a test case:
-
-test = """\
- d = sqrt(b**2 - 4*a*c)
-twoa = 2*a
- L = -b/twoa
- R = d/twoa
- A1 = L + R
- A2 = L - R\0
-"""
-
-# The program should print:
-
-# d = sqrt(b^2 - 4*a*c);twoa = 2*a; L = -b/twoa; R = d/twoa; A1 = L + R;
-#A2 = L - R
-#done
-
-# getline: delivers the next input line to its invoker
-# disassembler: grabs input lines from getline, and delivers them one
-# character at a time to squasher, also inserting a semicolon into
-# the stream between lines
-# squasher: grabs characters from disassembler and passes them on to
-# assembler, first replacing "**" with "^" and squashing runs of
-# whitespace
-# assembler: grabs characters from squasher and packs them into lines
-# with 72 character each, delivering each such line to putline;
-# when it sees a null byte, passes the last line to putline and
-# then kills all the coroutines
-# putline: grabs lines from assembler, and just prints them
-
-from Coroutine import *
-
-def getline(text):
- for line in string.splitfields(text, '\n'):
- co.tran(codisassembler, line)
-
-def disassembler():
- while 1:
- card = co.tran(cogetline)
- for i in range(len(card)):
- co.tran(cosquasher, card[i])
- co.tran(cosquasher, ';')
-
-def squasher():
- while 1:
- ch = co.tran(codisassembler)
- if ch == '*':
- ch2 = co.tran(codisassembler)
- if ch2 == '*':
- ch = '^'
- else:
- co.tran(coassembler, ch)
- ch = ch2
- if ch in ' \t':
- while 1:
- ch2 = co.tran(codisassembler)
- if ch2 not in ' \t':
- break
- co.tran(coassembler, ' ')
- ch = ch2
- co.tran(coassembler, ch)
-
-def assembler():
- line = ''
- while 1:
- ch = co.tran(cosquasher)
- if ch == '\0':
- break
- if len(line) == 72:
- co.tran(coputline, line)
- line = ''
- line = line + ch
- line = line + ' ' * (72 - len(line))
- co.tran(coputline, line)
- co.kill()
-
-def putline():
- while 1:
- line = co.tran(coassembler)
- print line
-
-import string
-co = Coroutine()
-cogetline = co.create(getline, test)
-coputline = co.create(putline)
-coassembler = co.create(assembler)
-codisassembler = co.create(disassembler)
-cosquasher = co.create(squasher)
-
-co.tran(coputline)
-print 'done'
-
-# end of example
diff --git a/Demo/threads/sync.py b/Demo/threads/sync.py
deleted file mode 100644
index a8556c48ef..0000000000
--- a/Demo/threads/sync.py
+++ /dev/null
@@ -1,603 +0,0 @@
-# Defines classes that provide synchronization objects. Note that use of
-# this module requires that your Python support threads.
-#
-# condition(lock=None) # a POSIX-like condition-variable object
-# barrier(n) # an n-thread barrier
-# event() # an event object
-# semaphore(n=1) # a semaphore object, with initial count n
-# mrsw() # a multiple-reader single-writer lock
-#
-# CONDITIONS
-#
-# A condition object is created via
-# import this_module
-# your_condition_object = this_module.condition(lock=None)
-#
-# As explained below, a condition object has a lock associated with it,
-# used in the protocol to protect condition data. You can specify a
-# lock to use in the constructor, else the constructor will allocate
-# an anonymous lock for you. Specifying a lock explicitly can be useful
-# when more than one condition keys off the same set of shared data.
-#
-# Methods:
-# .acquire()
-# acquire the lock associated with the condition
-# .release()
-# release the lock associated with the condition
-# .wait()
-# block the thread until such time as some other thread does a
-# .signal or .broadcast on the same condition, and release the
-# lock associated with the condition. The lock associated with
-# the condition MUST be in the acquired state at the time
-# .wait is invoked.
-# .signal()
-# wake up exactly one thread (if any) that previously did a .wait
-# on the condition; that thread will awaken with the lock associated
-# with the condition in the acquired state. If no threads are
-# .wait'ing, this is a nop. If more than one thread is .wait'ing on
-# the condition, any of them may be awakened.
-# .broadcast()
-# wake up all threads (if any) that are .wait'ing on the condition;
-# the threads are woken up serially, each with the lock in the
-# acquired state, so should .release() as soon as possible. If no
-# threads are .wait'ing, this is a nop.
-#
-# Note that if a thread does a .wait *while* a signal/broadcast is
-# in progress, it's guaranteeed to block until a subsequent
-# signal/broadcast.
-#
-# Secret feature: `broadcast' actually takes an integer argument,
-# and will wake up exactly that many waiting threads (or the total
-# number waiting, if that's less). Use of this is dubious, though,
-# and probably won't be supported if this form of condition is
-# reimplemented in C.
-#
-# DIFFERENCES FROM POSIX
-#
-# + A separate mutex is not needed to guard condition data. Instead, a
-# condition object can (must) be .acquire'ed and .release'ed directly.
-# This eliminates a common error in using POSIX conditions.
-#
-# + Because of implementation difficulties, a POSIX `signal' wakes up
-# _at least_ one .wait'ing thread. Race conditions make it difficult
-# to stop that. This implementation guarantees to wake up only one,
-# but you probably shouldn't rely on that.
-#
-# PROTOCOL
-#
-# Condition objects are used to block threads until "some condition" is
-# true. E.g., a thread may wish to wait until a producer pumps out data
-# for it to consume, or a server may wish to wait until someone requests
-# its services, or perhaps a whole bunch of threads want to wait until a
-# preceding pass over the data is complete. Early models for conditions
-# relied on some other thread figuring out when a blocked thread's
-# condition was true, and made the other thread responsible both for
-# waking up the blocked thread and guaranteeing that it woke up with all
-# data in a correct state. This proved to be very delicate in practice,
-# and gave conditions a bad name in some circles.
-#
-# The POSIX model addresses these problems by making a thread responsible
-# for ensuring that its own state is correct when it wakes, and relies
-# on a rigid protocol to make this easy; so long as you stick to the
-# protocol, POSIX conditions are easy to "get right":
-#
-# A) The thread that's waiting for some arbitrarily-complex condition
-# (ACC) to become true does:
-#
-# condition.acquire()
-# while not (code to evaluate the ACC):
-# condition.wait()
-# # That blocks the thread, *and* releases the lock. When a
-# # condition.signal() happens, it will wake up some thread that
-# # did a .wait, *and* acquire the lock again before .wait
-# # returns.
-# #
-# # Because the lock is acquired at this point, the state used
-# # in evaluating the ACC is frozen, so it's safe to go back &
-# # reevaluate the ACC.
-#
-# # At this point, ACC is true, and the thread has the condition
-# # locked.
-# # So code here can safely muck with the shared state that
-# # went into evaluating the ACC -- if it wants to.
-# # When done mucking with the shared state, do
-# condition.release()
-#
-# B) Threads that are mucking with shared state that may affect the
-# ACC do:
-#
-# condition.acquire()
-# # muck with shared state
-# condition.release()
-# if it's possible that ACC is true now:
-# condition.signal() # or .broadcast()
-#
-# Note: You may prefer to put the "if" clause before the release().
-# That's fine, but do note that anyone waiting on the signal will
-# stay blocked until the release() is done (since acquiring the
-# condition is part of what .wait() does before it returns).
-#
-# TRICK OF THE TRADE
-#
-# With simpler forms of conditions, it can be impossible to know when
-# a thread that's supposed to do a .wait has actually done it. But
-# because this form of condition releases a lock as _part_ of doing a
-# wait, the state of that lock can be used to guarantee it.
-#
-# E.g., suppose thread A spawns thread B and later wants to wait for B to
-# complete:
-#
-# In A: In B:
-#
-# B_done = condition() ... do work ...
-# B_done.acquire() B_done.acquire(); B_done.release()
-# spawn B B_done.signal()
-# ... some time later ... ... and B exits ...
-# B_done.wait()
-#
-# Because B_done was in the acquire'd state at the time B was spawned,
-# B's attempt to acquire B_done can't succeed until A has done its
-# B_done.wait() (which releases B_done). So B's B_done.signal() is
-# guaranteed to be seen by the .wait(). Without the lock trick, B
-# may signal before A .waits, and then A would wait forever.
-#
-# BARRIERS
-#
-# A barrier object is created via
-# import this_module
-# your_barrier = this_module.barrier(num_threads)
-#
-# Methods:
-# .enter()
-# the thread blocks until num_threads threads in all have done
-# .enter(). Then the num_threads threads that .enter'ed resume,
-# and the barrier resets to capture the next num_threads threads
-# that .enter it.
-#
-# EVENTS
-#
-# An event object is created via
-# import this_module
-# your_event = this_module.event()
-#
-# An event has two states, `posted' and `cleared'. An event is
-# created in the cleared state.
-#
-# Methods:
-#
-# .post()
-# Put the event in the posted state, and resume all threads
-# .wait'ing on the event (if any).
-#
-# .clear()
-# Put the event in the cleared state.
-#
-# .is_posted()
-# Returns 0 if the event is in the cleared state, or 1 if the event
-# is in the posted state.
-#
-# .wait()
-# If the event is in the posted state, returns immediately.
-# If the event is in the cleared state, blocks the calling thread
-# until the event is .post'ed by another thread.
-#
-# Note that an event, once posted, remains posted until explicitly
-# cleared. Relative to conditions, this is both the strength & weakness
-# of events. It's a strength because the .post'ing thread doesn't have to
-# worry about whether the threads it's trying to communicate with have
-# already done a .wait (a condition .signal is seen only by threads that
-# do a .wait _prior_ to the .signal; a .signal does not persist). But
-# it's a weakness because .clear'ing an event is error-prone: it's easy
-# to mistakenly .clear an event before all the threads you intended to
-# see the event get around to .wait'ing on it. But so long as you don't
-# need to .clear an event, events are easy to use safely.
-#
-# SEMAPHORES
-#
-# A semaphore object is created via
-# import this_module
-# your_semaphore = this_module.semaphore(count=1)
-#
-# A semaphore has an integer count associated with it. The initial value
-# of the count is specified by the optional argument (which defaults to
-# 1) passed to the semaphore constructor.
-#
-# Methods:
-#
-# .p()
-# If the semaphore's count is greater than 0, decrements the count
-# by 1 and returns.
-# Else if the semaphore's count is 0, blocks the calling thread
-# until a subsequent .v() increases the count. When that happens,
-# the count will be decremented by 1 and the calling thread resumed.
-#
-# .v()
-# Increments the semaphore's count by 1, and wakes up a thread (if
-# any) blocked by a .p(). It's an (detected) error for a .v() to
-# increase the semaphore's count to a value larger than the initial
-# count.
-#
-# MULTIPLE-READER SINGLE-WRITER LOCKS
-#
-# A mrsw lock is created via
-# import this_module
-# your_mrsw_lock = this_module.mrsw()
-#
-# This kind of lock is often useful with complex shared data structures.
-# The object lets any number of "readers" proceed, so long as no thread
-# wishes to "write". When a (one or more) thread declares its intention
-# to "write" (e.g., to update a shared structure), all current readers
-# are allowed to finish, and then a writer gets exclusive access; all
-# other readers & writers are blocked until the current writer completes.
-# Finally, if some thread is waiting to write and another is waiting to
-# read, the writer takes precedence.
-#
-# Methods:
-#
-# .read_in()
-# If no thread is writing or waiting to write, returns immediately.
-# Else blocks until no thread is writing or waiting to write. So
-# long as some thread has completed a .read_in but not a .read_out,
-# writers are blocked.
-#
-# .read_out()
-# Use sometime after a .read_in to declare that the thread is done
-# reading. When all threads complete reading, a writer can proceed.
-#
-# .write_in()
-# If no thread is writing (has completed a .write_in, but hasn't yet
-# done a .write_out) or reading (similarly), returns immediately.
-# Else blocks the calling thread, and threads waiting to read, until
-# the current writer completes writing or all the current readers
-# complete reading; if then more than one thread is waiting to
-# write, one of them is allowed to proceed, but which one is not
-# specified.
-#
-# .write_out()
-# Use sometime after a .write_in to declare that the thread is done
-# writing. Then if some other thread is waiting to write, it's
-# allowed to proceed. Else all threads (if any) waiting to read are
-# allowed to proceed.
-#
-# .write_to_read()
-# Use instead of a .write_in to declare that the thread is done
-# writing but wants to continue reading without other writers
-# intervening. If there are other threads waiting to write, they
-# are allowed to proceed only if the current thread calls
-# .read_out; threads waiting to read are only allowed to proceed
-# if there are are no threads waiting to write. (This is a
-# weakness of the interface!)
-
-import thread
-
-class condition:
- def __init__(self, lock=None):
- # the lock actually used by .acquire() and .release()
- if lock is None:
- self.mutex = thread.allocate_lock()
- else:
- if hasattr(lock, 'acquire') and \
- hasattr(lock, 'release'):
- self.mutex = lock
- else:
- raise TypeError, 'condition constructor requires ' \
- 'a lock argument'
-
- # lock used to block threads until a signal
- self.checkout = thread.allocate_lock()
- self.checkout.acquire()
-
- # internal critical-section lock, & the data it protects
- self.idlock = thread.allocate_lock()
- self.id = 0
- self.waiting = 0 # num waiters subject to current release
- self.pending = 0 # num waiters awaiting next signal
- self.torelease = 0 # num waiters to release
- self.releasing = 0 # 1 iff release is in progress
-
- def acquire(self):
- self.mutex.acquire()
-
- def release(self):
- self.mutex.release()
-
- def wait(self):
- mutex, checkout, idlock = self.mutex, self.checkout, self.idlock
- if not mutex.locked():
- raise ValueError, \
- "condition must be .acquire'd when .wait() invoked"
-
- idlock.acquire()
- myid = self.id
- self.pending = self.pending + 1
- idlock.release()
-
- mutex.release()
-
- while 1:
- checkout.acquire(); idlock.acquire()
- if myid < self.id:
- break
- checkout.release(); idlock.release()
-
- self.waiting = self.waiting - 1
- self.torelease = self.torelease - 1
- if self.torelease:
- checkout.release()
- else:
- self.releasing = 0
- if self.waiting == self.pending == 0:
- self.id = 0
- idlock.release()
- mutex.acquire()
-
- def signal(self):
- self.broadcast(1)
-
- def broadcast(self, num = -1):
- if num < -1:
- raise ValueError, '.broadcast called with num ' + `num`
- if num == 0:
- return
- self.idlock.acquire()
- if self.pending:
- self.waiting = self.waiting + self.pending
- self.pending = 0
- self.id = self.id + 1
- if num == -1:
- self.torelease = self.waiting
- else:
- self.torelease = min( self.waiting,
- self.torelease + num )
- if self.torelease and not self.releasing:
- self.releasing = 1
- self.checkout.release()
- self.idlock.release()
-
-class barrier:
- def __init__(self, n):
- self.n = n
- self.togo = n
- self.full = condition()
-
- def enter(self):
- full = self.full
- full.acquire()
- self.togo = self.togo - 1
- if self.togo:
- full.wait()
- else:
- self.togo = self.n
- full.broadcast()
- full.release()
-
-class event:
- def __init__(self):
- self.state = 0
- self.posted = condition()
-
- def post(self):
- self.posted.acquire()
- self.state = 1
- self.posted.broadcast()
- self.posted.release()
-
- def clear(self):
- self.posted.acquire()
- self.state = 0
- self.posted.release()
-
- def is_posted(self):
- self.posted.acquire()
- answer = self.state
- self.posted.release()
- return answer
-
- def wait(self):
- self.posted.acquire()
- if not self.state:
- self.posted.wait()
- self.posted.release()
-
-class semaphore:
- def __init__(self, count=1):
- if count <= 0:
- raise ValueError, 'semaphore count %d; must be >= 1' % count
- self.count = count
- self.maxcount = count
- self.nonzero = condition()
-
- def p(self):
- self.nonzero.acquire()
- while self.count == 0:
- self.nonzero.wait()
- self.count = self.count - 1
- self.nonzero.release()
-
- def v(self):
- self.nonzero.acquire()
- if self.count == self.maxcount:
- raise ValueError, '.v() tried to raise semaphore count above ' \
- 'initial value ' + `maxcount`
- self.count = self.count + 1
- self.nonzero.signal()
- self.nonzero.release()
-
-class mrsw:
- def __init__(self):
- # critical-section lock & the data it protects
- self.rwOK = thread.allocate_lock()
- self.nr = 0 # number readers actively reading (not just waiting)
- self.nw = 0 # number writers either waiting to write or writing
- self.writing = 0 # 1 iff some thread is writing
-
- # conditions
- self.readOK = condition(self.rwOK) # OK to unblock readers
- self.writeOK = condition(self.rwOK) # OK to unblock writers
-
- def read_in(self):
- self.rwOK.acquire()
- while self.nw:
- self.readOK.wait()
- self.nr = self.nr + 1
- self.rwOK.release()
-
- def read_out(self):
- self.rwOK.acquire()
- if self.nr <= 0:
- raise ValueError, \
- '.read_out() invoked without an active reader'
- self.nr = self.nr - 1
- if self.nr == 0:
- self.writeOK.signal()
- self.rwOK.release()
-
- def write_in(self):
- self.rwOK.acquire()
- self.nw = self.nw + 1
- while self.writing or self.nr:
- self.writeOK.wait()
- self.writing = 1
- self.rwOK.release()
-
- def write_out(self):
- self.rwOK.acquire()
- if not self.writing:
- raise ValueError, \
- '.write_out() invoked without an active writer'
- self.writing = 0
- self.nw = self.nw - 1
- if self.nw:
- self.writeOK.signal()
- else:
- self.readOK.broadcast()
- self.rwOK.release()
-
- def write_to_read(self):
- self.rwOK.acquire()
- if not self.writing:
- raise ValueError, \
- '.write_to_read() invoked without an active writer'
- self.writing = 0
- self.nw = self.nw - 1
- self.nr = self.nr + 1
- if not self.nw:
- self.readOK.broadcast()
- self.rwOK.release()
-
-# The rest of the file is a test case, that runs a number of parallelized
-# quicksorts in parallel. If it works, you'll get about 600 lines of
-# tracing output, with a line like
-# test passed! 209 threads created in all
-# as the last line. The content and order of preceding lines will
-# vary across runs.
-
-def _new_thread(func, *args):
- global TID
- tid.acquire(); id = TID = TID+1; tid.release()
- io.acquire(); alive.append(id); \
- print 'starting thread', id, '--', len(alive), 'alive'; \
- io.release()
- thread.start_new_thread( func, (id,) + args )
-
-def _qsort(tid, a, l, r, finished):
- # sort a[l:r]; post finished when done
- io.acquire(); print 'thread', tid, 'qsort', l, r; io.release()
- if r-l > 1:
- pivot = a[l]
- j = l+1 # make a[l:j] <= pivot, and a[j:r] > pivot
- for i in range(j, r):
- if a[i] <= pivot:
- a[j], a[i] = a[i], a[j]
- j = j + 1
- a[l], a[j-1] = a[j-1], pivot
-
- l_subarray_sorted = event()
- r_subarray_sorted = event()
- _new_thread(_qsort, a, l, j-1, l_subarray_sorted)
- _new_thread(_qsort, a, j, r, r_subarray_sorted)
- l_subarray_sorted.wait()
- r_subarray_sorted.wait()
-
- io.acquire(); print 'thread', tid, 'qsort done'; \
- alive.remove(tid); io.release()
- finished.post()
-
-def _randarray(tid, a, finished):
- io.acquire(); print 'thread', tid, 'randomizing array'; \
- io.release()
- for i in range(1, len(a)):
- wh.acquire(); j = randint(0,i); wh.release()
- a[i], a[j] = a[j], a[i]
- io.acquire(); print 'thread', tid, 'randomizing done'; \
- alive.remove(tid); io.release()
- finished.post()
-
-def _check_sort(a):
- if a != range(len(a)):
- raise ValueError, ('a not sorted', a)
-
-def _run_one_sort(tid, a, bar, done):
- # randomize a, and quicksort it
- # for variety, all the threads running this enter a barrier
- # at the end, and post `done' after the barrier exits
- io.acquire(); print 'thread', tid, 'randomizing', a; \
- io.release()
- finished = event()
- _new_thread(_randarray, a, finished)
- finished.wait()
-
- io.acquire(); print 'thread', tid, 'sorting', a; io.release()
- finished.clear()
- _new_thread(_qsort, a, 0, len(a), finished)
- finished.wait()
- _check_sort(a)
-
- io.acquire(); print 'thread', tid, 'entering barrier'; \
- io.release()
- bar.enter()
- io.acquire(); print 'thread', tid, 'leaving barrier'; \
- io.release()
- io.acquire(); alive.remove(tid); io.release()
- bar.enter() # make sure they've all removed themselves from alive
- ## before 'done' is posted
- bar.enter() # just to be cruel
- done.post()
-
-def test():
- global TID, tid, io, wh, randint, alive
- import random
- randint = random.randint
-
- TID = 0 # thread ID (1, 2, ...)
- tid = thread.allocate_lock() # for changing TID
- io = thread.allocate_lock() # for printing, and 'alive'
- wh = thread.allocate_lock() # for calls to random
- alive = [] # IDs of active threads
-
- NSORTS = 5
- arrays = []
- for i in range(NSORTS):
- arrays.append( range( (i+1)*10 ) )
-
- bar = barrier(NSORTS)
- finished = event()
- for i in range(NSORTS):
- _new_thread(_run_one_sort, arrays[i], bar, finished)
- finished.wait()
-
- print 'all threads done, and checking results ...'
- if alive:
- raise ValueError, ('threads still alive at end', alive)
- for i in range(NSORTS):
- a = arrays[i]
- if len(a) != (i+1)*10:
- raise ValueError, ('length of array', i, 'screwed up')
- _check_sort(a)
-
- print 'test passed!', TID, 'threads created in all'
-
-if __name__ == '__main__':
- test()
-
-# end of module
diff --git a/Demo/threads/telnet.py b/Demo/threads/telnet.py
deleted file mode 100644
index 3c70cb0038..0000000000
--- a/Demo/threads/telnet.py
+++ /dev/null
@@ -1,114 +0,0 @@
-# Minimal interface to the Internet telnet protocol.
-#
-# *** modified to use threads ***
-#
-# It refuses all telnet options and does not recognize any of the other
-# telnet commands, but can still be used to connect in line-by-line mode.
-# It's also useful to play with a number of other services,
-# like time, finger, smtp and even ftp.
-#
-# Usage: telnet host [port]
-#
-# The port may be a service name or a decimal port number;
-# it defaults to 'telnet'.
-
-
-import sys, os, time
-from socket import *
-import thread
-
-BUFSIZE = 8*1024
-
-# Telnet protocol characters
-
-IAC = chr(255) # Interpret as command
-DONT = chr(254)
-DO = chr(253)
-WONT = chr(252)
-WILL = chr(251)
-
-def main():
- if len(sys.argv) < 2:
- sys.stderr.write('usage: telnet hostname [port]\n')
- sys.exit(2)
- host = sys.argv[1]
- try:
- hostaddr = gethostbyname(host)
- except error:
- sys.stderr.write(sys.argv[1] + ': bad host name\n')
- sys.exit(2)
- #
- if len(sys.argv) > 2:
- servname = sys.argv[2]
- else:
- servname = 'telnet'
- #
- if '0' <= servname[:1] <= '9':
- port = eval(servname)
- else:
- try:
- port = getservbyname(servname, 'tcp')
- except error:
- sys.stderr.write(servname + ': bad tcp service name\n')
- sys.exit(2)
- #
- s = socket(AF_INET, SOCK_STREAM)
- #
- try:
- s.connect((host, port))
- except error, msg:
- sys.stderr.write('connect failed: ' + `msg` + '\n')
- sys.exit(1)
- #
- thread.start_new(child, (s,))
- parent(s)
-
-def parent(s):
- # read socket, write stdout
- iac = 0 # Interpret next char as command
- opt = '' # Interpret next char as option
- while 1:
- data, dummy = s.recvfrom(BUFSIZE)
- if not data:
- # EOF -- exit
- sys.stderr.write( '(Closed by remote host)\n')
- sys.exit(1)
- cleandata = ''
- for c in data:
- if opt:
- print ord(c)
-## print '(replying: ' + `opt+c` + ')'
- s.send(opt + c)
- opt = ''
- elif iac:
- iac = 0
- if c == IAC:
- cleandata = cleandata + c
- elif c in (DO, DONT):
- if c == DO: print '(DO)',
- else: print '(DONT)',
- opt = IAC + WONT
- elif c in (WILL, WONT):
- if c == WILL: print '(WILL)',
- else: print '(WONT)',
- opt = IAC + DONT
- else:
- print '(command)', ord(c)
- elif c == IAC:
- iac = 1
- print '(IAC)',
- else:
- cleandata = cleandata + c
- sys.stdout.write(cleandata)
- sys.stdout.flush()
-## print 'Out:', `cleandata`
-
-def child(s):
- # read stdin, write socket
- while 1:
- line = sys.stdin.readline()
-## print 'Got:', `line`
- if not line: break
- s.send(line)
-
-main()
diff --git a/Demo/tix/INSTALL.txt b/Demo/tix/INSTALL.txt
deleted file mode 100644
index ac70b68c80..0000000000
--- a/Demo/tix/INSTALL.txt
+++ /dev/null
@@ -1,89 +0,0 @@
-$Id$
-
-Installing Tix.py
-----------------
-
-0) To use Tix.py, you need Tcl/Tk (V8.3.3), Tix (V8.1.1) and Python (V2.1.1).
- Tix.py has been written and tested on a Intel Pentium running RH Linux 5.2
- and Mandrake Linux 7.0 and Windows with the above mentioned packages.
-
- Older versions, e.g. Tix 4.1 and Tk 8.0, might also work.
-
- There is nothing OS-specific in Tix.py itself so it should work on
- any machine with Tix and Python installed. You can get Tcl and Tk
- from http://dev.scriptics.com and Tix from http://tix.sourceforge.net.
-
-1) Build and install Tcl/Tk 8.3. Build and install Tix 8.1.
- Ensure that Tix is properly installed by running tixwish and executing
- the demo programs. Under Unix, use the --enable-shared configure option
- for all three. We recommend tcl8.3.3 for this release of Tix.py.
-
-2a) If you have a distribution like ActiveState with a tcl subdirectory
- of $PYTHONHOME, which contains the directories tcl8.3 and tk8.3,
- make a directory tix8.1 as well. Recursively copy the files from
- /library to $PYTHONHOME/lib/tix8.1, and copy the dynamic library
- (tix8183.dll or libtix8.1.8.3.so) to the same place as the tcl dynamic
- libraries ($PYTHONHOME/Dlls or lib/python-2.1/lib-dynload). In this
- case you are all installed, and you can skip to the end.
-
-2b) Modify Modules/Setup.dist and setup.py to change the version of the
- tix library from tix4.1.8.0 to tix8.1.8.3
- These modified files can be used for Tkinter with or without Tix.
-
-3) The default is to build dynamically, and use the Tcl 'package require'.
- To build statically, modify the Modules/Setup file to link in the Tix
- library according to the comments in the file. On Linux this looks like:
-
-# *** Always uncomment this (leave the leading underscore in!):
-_tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \
-# *** Uncomment and edit to reflect where your Tcl/Tk libraries are:
- -L/usr/local/lib \
-# *** Uncomment and edit to reflect where your Tcl/Tk headers are:
- -I/usr/local/include \
-# *** Uncomment and edit to reflect where your X11 header files are:
- -I/usr/X11R6/include \
-# *** Or uncomment this for Solaris:
-# -I/usr/openwin/include \
-# *** Uncomment and edit for BLT extension only:
-# -DWITH_BLT -I/usr/local/blt/blt8.0-unoff/include -lBLT8.0 \
-# *** Uncomment and edit for PIL (TkImaging) extension only:
-# (See http://www.pythonware.com/products/pil/ for more info)
-# -DWITH_PIL -I../Extensions/Imaging/libImaging tkImaging.c \
-# *** Uncomment and edit for TOGL extension only:
-# -DWITH_TOGL togl.c \
-# *** Uncomment and edit for Tix extension only:
- -DWITH_TIX -ltix8.1.8.3 \
-# *** Uncomment and edit to reflect your Tcl/Tk versions:
- -ltk8.3 -ltcl8.3 \
-# *** Uncomment and edit to reflect where your X11 libraries are:
- -L/usr/X11R6/lib \
-# *** Or uncomment this for Solaris:
-# -L/usr/openwin/lib \
-# *** Uncomment these for TOGL extension only:
-# -lGL -lGLU -lXext -lXmu \
-# *** Uncomment for AIX:
-# -lld \
-# *** Always uncomment this; X11 libraries to link with:
- -lX11
-
-4) Rebuild Python and reinstall.
-
-You should now have a working Tix implementation in Python. To see if all
-is as it should be, run the 'tixwidgets.py' script in the Demo/tix directory.
-Under X windows, do
- /usr/local/bin/python Demo/tix/tixwidgets.py
-
-If this does not work, you may need to tell python where to find
-the Tcl, Tk and Tix library files. This is done by setting the
-TCL_LIBRARY, TK_LIBRARY and TIX_LIBRARY environment variables. Try this:
-
- env TCL_LIBRARY=/usr/local/lib/tcl8.3 \
- TK_LIBRARY=/usr/local/lib/tk8.3 \
- TIX_LIBRARY=/usr/local/lib/tix8.1 \
- /usr/local/bin/python Demo/tix/tixwidgets.py
-
-
-If you find any bugs or have suggestions for improvement, please report them
-via http://tix.sourceforge.net
-
-
diff --git a/Demo/tix/README.txt b/Demo/tix/README.txt
deleted file mode 100644
index e0196ac3c7..0000000000
--- a/Demo/tix/README.txt
+++ /dev/null
@@ -1,19 +0,0 @@
-About Tix.py
------------
-
-Tix.py is based on an idea of Jean-Marc Lugrin (lugrin@ms.com) who wrote
-pytix (another Python-Tix marriage). Tix widgets are an attractive and
-useful extension to Tk. See http://tix.sourceforge.net
-for more details about Tix and how to get it.
-
-Features:
- 1) It is almost complete.
- 2) Tix widgets are represented by classes in Python. Sub-widgets
- are members of the mega-widget class. For example, if a
- particular TixWidget (e.g. ScrolledText) has an embedded widget
- (Text in this case), it is possible to call the methods of the
- child directly.
- 3) The members of the class are created automatically. In the case
- of widgets like ButtonBox, the members are added dynamically.
-
-
diff --git a/Demo/tix/bitmaps/about.xpm b/Demo/tix/bitmaps/about.xpm
deleted file mode 100755
index 33ffcc06ef..0000000000
--- a/Demo/tix/bitmaps/about.xpm
+++ /dev/null
@@ -1,50 +0,0 @@
-/* XPM */
-static char * about_xpm[] = {
-"50 40 7 1",
-" s None c None",
-". c black",
-"X c white",
-"o c gray70",
-"O c navy",
-"+ c red",
-"@ c yellow",
-" ",
-" ",
-" ",
-" ................................. ",
-" ..XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXoo. ",
-" .XooooooooooooooooooooooooooooooXo. ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXooXo. ",
-" ..oooooooooooooooooooooooooooooooXo. ",
-" ...............................XoXo. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo.++++ ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo+++ ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo+++++ ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo++++++ ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo+++ + ",
-" .OOOOO@@@@@OOOOOOOOOOOOOOOOOOO.Xo++. ",
-" .OOOOOOO@OOOOO@OOOOOOOOOOOOOOO.XoXo. ",
-" .OOOOOOO@OOOOOOOOOOOOOOOOOOOOO.XoXo. ",
-" .OOOOOOO@OOOO@@OOO@OOO@OOOOOOO.XoXo. ",
-" .OOOOOOO@OOOOO@OOOO@O@OOOOOOOO.XoXo. ",
-" .OOOOOOO@OOOOO@OOOOO@OOOOOOOOO.XoXo. ",
-" .OOOOOOO@OOOOO@OOOOO@OOOOOOOOO.XoXo. ",
-" .OOOOOOO@OOOOO@OOOO@O@OOOOOOOO.XoXo. ",
-" .OOOOOOO@OOOO@@@OO@OOO@OOOOOOO.XoXo. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo.. ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo ",
-" OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.X. ",
-" ............................. ",
-" ",
-" ",
-" "};
diff --git a/Demo/tix/bitmaps/bold.xbm b/Demo/tix/bitmaps/bold.xbm
deleted file mode 100755
index ebff8d1178..0000000000
--- a/Demo/tix/bitmaps/bold.xbm
+++ /dev/null
@@ -1,6 +0,0 @@
-#define bold_width 16
-#define bold_height 16
-static unsigned char bold_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0xfc, 0x07, 0xfc, 0x0f, 0x18, 0x1c, 0x18, 0x18,
- 0x18, 0x18, 0x18, 0x1c, 0xf8, 0x0f, 0xf8, 0x0f, 0x18, 0x18, 0x18, 0x30,
- 0x18, 0x30, 0x18, 0x38, 0xfc, 0x3f, 0xfc, 0x1f};
diff --git a/Demo/tix/bitmaps/capital.xbm b/Demo/tix/bitmaps/capital.xbm
deleted file mode 100755
index fb4e0703b1..0000000000
--- a/Demo/tix/bitmaps/capital.xbm
+++ /dev/null
@@ -1,6 +0,0 @@
-#define capital_width 16
-#define capital_height 16
-static unsigned char capital_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x08, 0x30, 0x0c, 0x30, 0x06,
- 0x30, 0x03, 0xb0, 0x01, 0xf0, 0x00, 0xf0, 0x00, 0xf0, 0x01, 0xb0, 0x03,
- 0x30, 0x07, 0x30, 0x0e, 0x30, 0x1c, 0x00, 0x00};
diff --git a/Demo/tix/bitmaps/centerj.xbm b/Demo/tix/bitmaps/centerj.xbm
deleted file mode 100755
index 9d2c064834..0000000000
--- a/Demo/tix/bitmaps/centerj.xbm
+++ /dev/null
@@ -1,6 +0,0 @@
-#define centerj_width 16
-#define centerj_height 16
-static unsigned char centerj_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3e, 0x00, 0x00, 0xc0, 0x0d,
- 0x00, 0x00, 0x58, 0x77, 0x00, 0x00, 0xb0, 0x3b, 0x00, 0x00, 0xdc, 0xf7,
- 0x00, 0x00, 0xf0, 0x3e, 0x00, 0x00, 0xd8, 0x7e};
diff --git a/Demo/tix/bitmaps/combobox.xbm b/Demo/tix/bitmaps/combobox.xbm
deleted file mode 100755
index f5947f57b4..0000000000
--- a/Demo/tix/bitmaps/combobox.xbm
+++ /dev/null
@@ -1,14 +0,0 @@
-#define combobox_width 32
-#define combobox_height 32
-static unsigned char combobox_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0xfc, 0xff, 0xff, 0x3e, 0x04, 0x00, 0x80, 0x2a, 0x04, 0x00, 0x80, 0x2a,
- 0x04, 0x00, 0x80, 0x2a, 0x04, 0x00, 0x80, 0x2b, 0xfc, 0xff, 0xff, 0x3e,
- 0x08, 0x00, 0x00, 0x20, 0x08, 0x00, 0x00, 0x3e, 0x08, 0x00, 0x00, 0x2a,
- 0x28, 0x49, 0x00, 0x2a, 0x08, 0x00, 0x00, 0x3e, 0x08, 0x00, 0x00, 0x22,
- 0x08, 0x00, 0x00, 0x22, 0x28, 0x49, 0x12, 0x22, 0x08, 0x00, 0x00, 0x22,
- 0x08, 0x00, 0x00, 0x22, 0x08, 0x00, 0x00, 0x22, 0x28, 0x49, 0x02, 0x22,
- 0x08, 0x00, 0x00, 0x3e, 0x08, 0x00, 0x00, 0x2a, 0x08, 0x00, 0x00, 0x2a,
- 0xf8, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
diff --git a/Demo/tix/bitmaps/combobox.xpm b/Demo/tix/bitmaps/combobox.xpm
deleted file mode 100755
index d0234ab8e2..0000000000
--- a/Demo/tix/bitmaps/combobox.xpm
+++ /dev/null
@@ -1,49 +0,0 @@
-/* XPM */
-static char * combobox_xpm[] = {
-"50 40 6 1",
-" s None c None",
-". c black",
-"X c white",
-"o c #FFFF80808080",
-"O c gray70",
-"+ c #808000008080",
-" ",
-" ",
-" ",
-" .................................... XXXXXXX ",
-" .ooooooooooooooooooooooooooooooooooX X . . ",
-" .ooooooooooooooooooooooooooooooooooX X . . ",
-" .oooo.oooooooooooooooooooooooooooooX X . . ",
-" .oo.o..oo.o.oo.o.ooooooooooooooooooX X . . ",
-" .o..o.o.o.oo.oo.oo.ooooooooooooooooX X ... . ",
-" .oo.oo.oo.o.oo.ooo.ooooooooooooooooX X . . ",
-" .ooooooooooooooooooooooooooooooooooX X . ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X...... ",
-" ",
-" ",
-" ",
-" XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ",
-" X............................................ ",
-" X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.OOOOX. ",
-" X.O+OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.OX OX. ",
-" X.O++OOO+OO+++OOOOOOOOOOOOOOOOOOOOOOOX.X ..X. ",
-" X.O+O+O+OOO+O+OOOOOOOOOOOOOOOOOOOOOOOX.OOOOX. ",
-" X.O++OOO+OO+++OOOOOOOOOOOOOOOOOOOOOOOX.OOOOX. ",
-" X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.XXXXX. ",
-" X.O.....X..........................OOX.X .X. ",
-" X.OX...XXX.X.XX.XX.................OOX.X .X. ",
-" X.OX.X..X..X.XX..XX.X..............OOX.X .X. ",
-" X.O.X...X..X.X...X..X..............OOX.X .X. ",
-" X.OOOOOOOOOOOOOOOOOOOOOOOO+OOOOOOOOOOX.X .X. ",
-" X.OOOOOOOOO+OOO+OOOOO+OOOO+OOOOOOOOOOX.X .X. ",
-" X.O+++OO+OO+O+OO++O++OO+OO+OOOOOOOOOOX.X...X. ",
-" X.OO+OO++OO+O+OO+OOO+OO+O++OOOOOOOOOOX.OOOOX. ",
-" X.OOOOOOOO+OOOOO++OO+OOOOOOOOOOOOOOOOX.OOOOX. ",
-" X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.X .X. ",
-" X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.O .OX. ",
-" X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.OOOOX. ",
-" X.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.XXXXX. ",
-" X............................................ ",
-" ",
-" ",
-" "};
diff --git a/Demo/tix/bitmaps/combobox.xpm.1 b/Demo/tix/bitmaps/combobox.xpm.1
deleted file mode 100755
index 63792a4908..0000000000
--- a/Demo/tix/bitmaps/combobox.xpm.1
+++ /dev/null
@@ -1,47 +0,0 @@
-/* XPM */
-static char * combobox_xpm[] = {
-"50 40 4 1",
-" s None c None",
-". c black",
-"X c #FFFF80808080",
-"o c gray70",
-" ",
-" ",
-" ",
-" .................................... ....... ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . . . ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . . . ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . . . ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . . . ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . ... . ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . . . ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . . ",
-" .................................... ....... ",
-" ",
-" ............................................. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .o...................................o.ooooo. ",
-" .o...................................o.ooooo. ",
-" .o...................................o.ooooo. ",
-" .o...................................o.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" .ooooooooooooooooooooooooooooooooooooo.ooooo. ",
-" ............................................. ",
-" ",
-" ",
-" ",
-" ",
-" "};
diff --git a/Demo/tix/bitmaps/drivea.xbm b/Demo/tix/bitmaps/drivea.xbm
deleted file mode 100755
index 83c636c670..0000000000
--- a/Demo/tix/bitmaps/drivea.xbm
+++ /dev/null
@@ -1,14 +0,0 @@
-#define drivea_width 32
-#define drivea_height 32
-static unsigned char drivea_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0xf8, 0xff, 0xff, 0x1f, 0x08, 0x00, 0x00, 0x18, 0xa8, 0xaa, 0xaa, 0x1a,
- 0x48, 0x55, 0xd5, 0x1d, 0xa8, 0xaa, 0xaa, 0x1b, 0x48, 0x55, 0x55, 0x1d,
- 0xa8, 0xfa, 0xaf, 0x1a, 0xc8, 0xff, 0xff, 0x1d, 0xa8, 0xfa, 0xaf, 0x1a,
- 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xaa, 0xaa, 0x1a, 0x48, 0x55, 0x55, 0x1d,
- 0xa8, 0xaa, 0xaa, 0x1a, 0xf8, 0xff, 0xff, 0x1f, 0xf8, 0xff, 0xff, 0x1f,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
diff --git a/Demo/tix/bitmaps/drivea.xpm b/Demo/tix/bitmaps/drivea.xpm
deleted file mode 100755
index 4d274b995f..0000000000
--- a/Demo/tix/bitmaps/drivea.xpm
+++ /dev/null
@@ -1,43 +0,0 @@
-/* XPM */
-static char * drivea_xpm[] = {
-/* width height ncolors chars_per_pixel */
-"32 32 5 1",
-/* colors */
-" s None c None",
-". c #000000000000",
-"X c white",
-"o c #c000c000c000",
-"O c #800080008000",
-/* pixels */
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" .......................... ",
-" .XXXXXXXXXXXXXXXXXXXXXXXo. ",
-" .XooooooooooooooooooooooO. ",
-" .Xooooooooooooooooo..oooO. ",
-" .Xooooooooooooooooo..oooO. ",
-" .XooooooooooooooooooooooO. ",
-" .Xoooooooo.......oooooooO. ",
-" .Xoo...................oO. ",
-" .Xoooooooo.......oooooooO. ",
-" .XooooooooooooooooooooooO. ",
-" .XooooooooooooooooooooooO. ",
-" .XooooooooooooooooooooooO. ",
-" .XooooooooooooooooooooooO. ",
-" .oOOOOOOOOOOOOOOOOOOOOOOO. ",
-" .......................... ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" "};
diff --git a/Demo/tix/bitmaps/exit.xpm b/Demo/tix/bitmaps/exit.xpm
deleted file mode 100755
index 505a07bdf6..0000000000
--- a/Demo/tix/bitmaps/exit.xpm
+++ /dev/null
@@ -1,48 +0,0 @@
-/* XPM */
-static char * exit_xpm[] = {
-"50 40 5 1",
-" s None c None",
-". c black",
-"X c white",
-"o c #000080800000",
-"O c yellow",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ....................................... ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. ",
-" .XoooooooooooooooooooooooooooooooooooX. ",
-" .XoooooooooooooooooooooooooooooooooooX. ",
-" .XoooooooooooooooooooooooOoooooooooooX. ",
-" .XoooooooooooooooooooooooOOooooooooooX. ",
-" .XoooooooooooooooooooooooOOOoooooooooX. ",
-" .XoooooOOOOOOOOOOOOOOOOOOOOOOooooooooX. ",
-" .XoooooOOOOOOOOOOOOOOOOOOOOOOOoooooooX. ",
-" .XoooooOOOOOOOOOOOOOOOOOOOOOOOOooooooX. ",
-" .XoooooOOOOOOOOOOOOOOOOOOOOOOOOOoooooX. ",
-" .XoooooOOOOOOOOOOOOOOOOOOOOOOOOooooooX. ",
-" .XoooooOOOOOOOOOOOOOOOOOOOOOOOoooooooX. ",
-" .XoooooOOOOOOOOOOOOOOOOOOOOOOooooooooX. ",
-" .XoooooooooooooooooooooooOOOoooooooooX. ",
-" .XoooooooooooooooooooooooOOooooooooooX. ",
-" .XoooooooooooooooooooooooOoooooooooooX. ",
-" .XoooooooooooooooooooooooooooooooooooX. ",
-" .XoooooooooooooooooooooooooooooooooooX. ",
-" .XoooooooooooooooooooooooooooooooooooX. ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. ",
-" ....................................... ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" "};
diff --git a/Demo/tix/bitmaps/filebox.xbm b/Demo/tix/bitmaps/filebox.xbm
deleted file mode 100755
index c8f7ac255b..0000000000
--- a/Demo/tix/bitmaps/filebox.xbm
+++ /dev/null
@@ -1,14 +0,0 @@
-#define filebox_width 32
-#define filebox_height 32
-static unsigned char filebox_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0x3f, 0x04, 0x00, 0x00, 0x20,
- 0xe4, 0xff, 0xff, 0x27, 0x24, 0x00, 0x00, 0x24, 0x24, 0x00, 0x00, 0x24,
- 0xe4, 0xff, 0xff, 0x27, 0x04, 0x00, 0x00, 0x20, 0xe4, 0x7f, 0xfe, 0x27,
- 0x24, 0x50, 0x02, 0x25, 0x24, 0x40, 0x02, 0x24, 0x24, 0x50, 0x02, 0x25,
- 0x24, 0x40, 0x02, 0x24, 0x24, 0x50, 0x02, 0x25, 0x24, 0x40, 0x02, 0x24,
- 0x24, 0x50, 0x02, 0x25, 0xe4, 0x7f, 0xfe, 0x27, 0x04, 0x00, 0x00, 0x20,
- 0xe4, 0xff, 0xff, 0x27, 0x24, 0x00, 0x00, 0x24, 0x24, 0x00, 0x00, 0x24,
- 0xe4, 0xff, 0xff, 0x27, 0x04, 0x00, 0x00, 0x20, 0xfc, 0xff, 0xff, 0x3f,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
diff --git a/Demo/tix/bitmaps/filebox.xpm b/Demo/tix/bitmaps/filebox.xpm
deleted file mode 100755
index 7377ee60e6..0000000000
--- a/Demo/tix/bitmaps/filebox.xpm
+++ /dev/null
@@ -1,49 +0,0 @@
-/* XPM */
-static char * filebox_xpm[] = {
-"50 40 6 1",
-" s None c None",
-". c white",
-"X c gray80",
-"o c black",
-"O c #FFFF80808080",
-"+ c gray70",
-" ",
-" ",
-" ",
-" ............................................ ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXooXooXoXooXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXooXooXoXooXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXooooooooooooooooooooooooooooooooooooo.XXo ",
-" .XXoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XXo ",
-" .XXoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XXo ",
-" .XX......................................XXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXoooooooooooooooo.XXXXoooooooooooooooo.XXo ",
-" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ",
-" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ",
-" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ",
-" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ",
-" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ",
-" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ",
-" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ",
-" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ",
-" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ",
-" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ",
-" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ",
-" .XX.................XXXX.................XXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXooXooXoXooXoXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXooXooXoXooXoXooXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXoooooooooooooooooooooooooooooooooooooo.Xo ",
-" .XXoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo ",
-" .XXoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo ",
-" .XX.......................................Xo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .ooooooooooooooooooooooooooooooooooooooooooo ",
-" ",
-" ",
-" "};
diff --git a/Demo/tix/bitmaps/italic.xbm b/Demo/tix/bitmaps/italic.xbm
deleted file mode 100755
index 169c3cb75f..0000000000
--- a/Demo/tix/bitmaps/italic.xbm
+++ /dev/null
@@ -1,6 +0,0 @@
-#define italic_width 16
-#define italic_height 16
-static unsigned char italic_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x80, 0x3f, 0x00, 0x06, 0x00, 0x06,
- 0x00, 0x03, 0x00, 0x03, 0x80, 0x01, 0x80, 0x01, 0xc0, 0x00, 0xc0, 0x00,
- 0x60, 0x00, 0x60, 0x00, 0xfc, 0x01, 0xfc, 0x01};
diff --git a/Demo/tix/bitmaps/justify.xbm b/Demo/tix/bitmaps/justify.xbm
deleted file mode 100755
index bba660acec..0000000000
--- a/Demo/tix/bitmaps/justify.xbm
+++ /dev/null
@@ -1,6 +0,0 @@
-#define justify_width 16
-#define justify_height 16
-static unsigned char justify_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xec, 0xdb, 0x00, 0x00, 0x7c, 0xdb,
- 0x00, 0x00, 0xbc, 0xf7, 0x00, 0x00, 0xdc, 0xde, 0x00, 0x00, 0x6c, 0xdf,
- 0x00, 0x00, 0x6c, 0xef, 0x00, 0x00, 0xdc, 0xdf};
diff --git a/Demo/tix/bitmaps/leftj.xbm b/Demo/tix/bitmaps/leftj.xbm
deleted file mode 100755
index 5f8e006f4e..0000000000
--- a/Demo/tix/bitmaps/leftj.xbm
+++ /dev/null
@@ -1,6 +0,0 @@
-#define leftj_width 16
-#define leftj_height 16
-static unsigned char leftj_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0x6d, 0x00, 0x00, 0xdc, 0x01,
- 0x00, 0x00, 0xec, 0x0e, 0x00, 0x00, 0xfc, 0x7e, 0x00, 0x00, 0xdc, 0x03,
- 0x00, 0x00, 0x6c, 0x3b, 0x00, 0x00, 0x6c, 0x1f};
diff --git a/Demo/tix/bitmaps/netw.xbm b/Demo/tix/bitmaps/netw.xbm
deleted file mode 100755
index a684d65d4b..0000000000
--- a/Demo/tix/bitmaps/netw.xbm
+++ /dev/null
@@ -1,14 +0,0 @@
-#define netw_width 32
-#define netw_height 32
-static unsigned char netw_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0x02, 0x40,
- 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x52,
- 0x00, 0x00, 0x0a, 0x52, 0x00, 0x00, 0x8a, 0x51, 0x00, 0x00, 0x0a, 0x50,
- 0x00, 0x00, 0x4a, 0x50, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x50,
- 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x02, 0x40, 0xfe, 0x7f, 0x52, 0x55,
- 0x02, 0x40, 0xaa, 0x6a, 0xfa, 0x5f, 0xfe, 0x7f, 0x0a, 0x50, 0xfe, 0x7f,
- 0x0a, 0x52, 0x80, 0x00, 0x0a, 0x52, 0x80, 0x00, 0x8a, 0x51, 0x80, 0x00,
- 0x0a, 0x50, 0x80, 0x00, 0x4a, 0x50, 0x80, 0x00, 0x0a, 0x50, 0xe0, 0x03,
- 0x0a, 0x50, 0x20, 0x02, 0xfa, 0xdf, 0x3f, 0x03, 0x02, 0x40, 0xa0, 0x02,
- 0x52, 0x55, 0xe0, 0x03, 0xaa, 0x6a, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00,
- 0xfe, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
diff --git a/Demo/tix/bitmaps/netw.xpm b/Demo/tix/bitmaps/netw.xpm
deleted file mode 100755
index fff6593bca..0000000000
--- a/Demo/tix/bitmaps/netw.xpm
+++ /dev/null
@@ -1,45 +0,0 @@
-/* XPM */
-static char * netw_xpm[] = {
-/* width height ncolors chars_per_pixel */
-"32 32 7 1",
-/* colors */
-" s None c None",
-". c #000000000000",
-"X c white",
-"o c #c000c000c000",
-"O c #404040",
-"+ c blue",
-"@ c red",
-/* pixels */
-" ",
-" .............. ",
-" .XXXXXXXXXXXX. ",
-" .XooooooooooO. ",
-" .Xo.......XoO. ",
-" .Xo.++++o+XoO. ",
-" .Xo.++++o+XoO. ",
-" .Xo.++oo++XoO. ",
-" .Xo.++++++XoO. ",
-" .Xo.+o++++XoO. ",
-" .Xo.++++++XoO. ",
-" .Xo.XXXXXXXoO. ",
-" .XooooooooooO. ",
-" .Xo@ooo....oO. ",
-" .............. .XooooooooooO. ",
-" .XXXXXXXXXXXX. .XooooooooooO. ",
-" .XooooooooooO. .OOOOOOOOOOOO. ",
-" .Xo.......XoO. .............. ",
-" .Xo.++++o+XoO. @ ",
-" .Xo.++++o+XoO. @ ",
-" .Xo.++oo++XoO. @ ",
-" .Xo.++++++XoO. @ ",
-" .Xo.+o++++XoO. @ ",
-" .Xo.++++++XoO. ..... ",
-" .Xo.XXXXXXXoO. .XXX. ",
-" .XooooooooooO.@@@@@@.X O. ",
-" .Xo@ooo....oO. .OOO. ",
-" .XooooooooooO. ..... ",
-" .XooooooooooO. ",
-" .OOOOOOOOOOOO. ",
-" .............. ",
-" "};
diff --git a/Demo/tix/bitmaps/optmenu.xpm b/Demo/tix/bitmaps/optmenu.xpm
deleted file mode 100755
index 63bab81299..0000000000
--- a/Demo/tix/bitmaps/optmenu.xpm
+++ /dev/null
@@ -1,48 +0,0 @@
-/* XPM */
-static char * optmenu_xpm[] = {
-"50 40 5 1",
-" s None c None",
-". c white",
-"X c gray80",
-"o c gray50",
-"O c black",
-" ",
-" ",
-" .............................. ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXXOXOXXOXXOXXXXOOXXXXXXXXXXo ",
-" .XXXOXOXXOXOXXXOXXOXXXXXXXXXXo ",
-" .XXXXOXXOXXOXXXOXXXOXXXXXXXXXo ",
-" .XXXXOXXXOXXOOXXOXOXXXXXXXXXXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo.............o ",
-" .............................o o ",
-" ..XXXOXXXXXOXXXXXXXXOXXXXXXXOo o ",
-" ..XXOXOXOXXOXOXXXOXXOXXXXXXXOo ...... o ",
-" ..XXXOXXXOXXOXXXOXXXOXXXXXXXOo . o o ",
-" ..XXOXXXOXXXOXOXXOXXOXXXXXXXOo . o o ",
-" ..XXXXXXXXXXXXXXXXXXXXXXXXXXOo .ooooo o ",
-" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOo o ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo o ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXooooooooooooooo ",
-" .XXXXOXXXXXOXXXXXXXXXXXXXXXXXo ",
-" .XXXOXXXXXXXXXOXXXXXXXXXXXXXXo ",
-" .XXXXOXXOXXOXOXOXXXXXXXXXXXXXo ",
-" .XXXXXOXXOXOXXXXXXXXXXXXXXXXXo ",
-" .XXXXXXXXXXXXXOXXXXXXXXXXXXXXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXXOXOXXXXXXXOXOXXXXXOXXXXXXo ",
-" .XXXXXOXOXOXXOXXXXXOXXOXXXXXXo ",
-" .XXXXOXXOXOXOXXXOXOXOXXOXXXXXo ",
-" .XXXOXXXXOXXOXXXOXXOXXXXOXXXXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ",
-" oooooooooooooooooooooooooooooo ",
-" ",
-" ",
-" ",
-" "};
diff --git a/Demo/tix/bitmaps/rightj.xbm b/Demo/tix/bitmaps/rightj.xbm
deleted file mode 100755
index 1d438e0090..0000000000
--- a/Demo/tix/bitmaps/rightj.xbm
+++ /dev/null
@@ -1,6 +0,0 @@
-#define rightj_width 16
-#define rightj_height 16
-static unsigned char rightj_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xdb, 0x00, 0x00, 0x70, 0xdb,
- 0x00, 0x00, 0x00, 0xef, 0x00, 0x00, 0xd8, 0xde, 0x00, 0x00, 0xc0, 0xdd,
- 0x00, 0x00, 0xa0, 0xef, 0x00, 0x00, 0xd8, 0xde};
diff --git a/Demo/tix/bitmaps/select.xpm b/Demo/tix/bitmaps/select.xpm
deleted file mode 100755
index 392e5a0834..0000000000
--- a/Demo/tix/bitmaps/select.xpm
+++ /dev/null
@@ -1,52 +0,0 @@
-/* XPM */
-static char * select_xpm[] = {
-"50 40 9 1",
-" s None c None",
-". c black",
-"X c gray95",
-"o c gray50",
-"O c gray70",
-"+ c navy",
-"@ c #000080800000",
-"# c #808000000000",
-"$ c white",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" .............................................. ",
-" .XXXXXXXXXXooooooooooooXXXXXXXXXXXoXXXXXXXXXX. ",
-" .X ooOOOOOOOOOOXX oX o. ",
-" .X ooOOOOOOOOOOXX oX o. ",
-" .X ++++ ooOOOOOOOOOOXX ... oX @ o. ",
-" .X +++++ ooOOOOOOOOOOXX . . oX @@@ o. ",
-" .X +++ + ooOOOOOOOOOOXX . . oX @ @ o. ",
-" .X + + ooOO#####OOOXX . . oX @ @ o. ",
-" .X + + ooOO#OOO##OOXX . oX @ @ o. ",
-" .X + + ooO##OOOO##OXX . oX @ @ o. ",
-" .X ++ ++ ooO###OOO#OOXX . oX @ @ o. ",
-" .X +++++++ ooO#######OOXX . oX @ @ o. ",
-" .X + + ooO##O#OO#OOXX . oX @ @ o. ",
-" .X + ++ ooO##OOOOO#OXX . . oX @ @ o. ",
-" .X + + ooOO#OOOOO#OXX . . oX @ @@ o. ",
-" .X + ++ ooOO#OOOOO#OXX .... oX @@@@@ o. ",
-" .X ooOO######OOXX oX o. ",
-" .X ooOOOOOOOOOOXX $oX o. ",
-" .XoooooooooooXXXXXXXXXXXoooooooooooXooooooooo. ",
-" .............................................. ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" "};
diff --git a/Demo/tix/bitmaps/tix.gif b/Demo/tix/bitmaps/tix.gif
deleted file mode 100755
index e7d51a086cc20c9a402e953237850ffba4d81844..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcwPel00001
literal 11042
zcwPY_E8WybNk%v~Vf+Bq0OJ4v00030|Nj60{{R4j{{R4jf`b450D=Gj!^6V>f&hYo
z009300D^)50000000000EC2ui0Q>;e06+x)5XecZy*TU5yZ>M)j$~;DXo?Q$AfUn<
z&v6jD^lZ<#(9?sUa7c6seZkw!m^==VOk8oATvD&WfYZk{cDcD67D(1<$Wf!pIG_YL)C7%{D`W8(
z#sL5WSt^{Z)(tT*a^T1Ua6%RsXrQT60tP~&kQ%@MQWXZ=WDQVo;8dt!nS!+%)#=l+
zW}OyDo3&}xrUVWYTsoFuS*UBFrX98@Q{wRGDQZTr4;>vVP6h6g~0)=ay0<^g6`3kV!|6Tinn-;Hv!
z>_+2my@X?-JV35x%eABLeQmd(YU$YBVlCZJ?A`3(QJmi0^bz4-vWlG7sf_Uo;FHih
zp$zqa{kQ`U+!bp*YG$@jVWt=VSOQk}+<)NFW?E}05){UJhxA9s;p85E#4dlqI=vV!VN1#Tx8#uV1_B?m|`kmfSC%UiDrQMS;rTG
zxt*3^bY2|^rc?T{m8SuF^4V0H2dIgrpn~pZXgaM-Nn$yhD0XEF6v>Cl9;J987nzsZ
z=jWb*rg^5PW~N1`0sskVpG;qdgjRNNhWAztnCkcCrkb*a=BK0Pnx+_xa99kZzSZ#P
zM83l3%aobMdRMIWDNrW=pmLF_Kvi-zcVAqq&Y9h6+%=QxWcgv*s+ylVHK?<)Hp{Cc
zh6QCtqr@?W3nr#$7!RtG-IpwxdR@vVZf1q6sdGX`Wo?+O!u3>uY)!aTh2AoIXH%T=
z`DK~}pewNg0&v`$P3DYa?=)=eL@aQV=28x2sp^Yg%Mv53uy)#QaHUiuh#!H;y`gxeE=YhY1m_GtSPle
zb~R*?Y`1M!R4}^8EVcSU%WSBE20-p$L`6c#i0qnJH6B(6a1R|>wtH+I;D(v+WKrGO
zvRQrpY3`X^T}tHtf!c=Gu;c#vD=Mz!o@@G`f2LVW%63=-4koDY)
zt1*Li;bX!AumBLG9Swc^W6HO}5*rL|FlXO_OJ`Oko~@{+gpu>0#2^Q}F~J36gNjco
zx`v!5RbwJJY({a46~P3^LkQ+;;qG>azPL1pJQ8HpZv_zVTA12IN`!{H=ltSLkUC7O7n4(&AEdY;6N1ZOonmxNl^9>^q>f>=RFdd(0g+7p#XJ^3|2>n
zO*(4-cI`}H>)u(2i>^QrJrQUdW>HUJJ=C3V@MnBt7c4OhhoNdLCmduD4ypNO2Z)0u
z$+p*s^k@_ph!96jO!*TUW{8%DIioN}L=IZOVh@yRX$}y&(44C0H>S+$$ey%~HTbP|
zrL1Nzo?6DAUb3vY3@0e32Gw@(K%p{4+$qMGO0k}m9c?|#ImlX5q(qSyVZq?OpZFs*%A&6`0%Gi9mvgBA~vl)*xZfEQkA?Y
z2!%ac9$dN;78K6xJM^nxgVvUN;Kd_C^l(i|Rxjm5%jzo3@LOo~d@uTYmPGla)+m
z?#8}a+qzQ%)K$jVv^goZip49=jZ~8LzrO6r#eT|l^+we(Z-$jHjm?8aJrN3L@3OJ%
zP~ogz_Og8eYE;vMA;(PRWp2-pP5}dQ@)%T}FApkE!YpPLYXfpkdVw*zO!8eG%gJCP!(kbDDc2qQ*xiHyqsT-(DCp`9boMRm8Rif;Q
z?Yy?SoEmN8dvU-gZeuHS5)0VN(SS?$J?a#&i#xgp{qSWA)#yg2rp#qzNB|xXoFV?2
zsHns_Ws%jmbjA73PgxahrR4#wJkP4Wx~uc5upyLHpLDTsQ@<+{t^~M5tRIi^a_Twr
zY;JSd$?+_8eb!6o-`vedq1-5z0(71ZPs%1`S9
z<5THs)u)XIP*73*YHW2X4JnmgripPr_c-0eq3y2#Sg+WCb}g;{GxaN62SYw{w>0~=
zWDV0ZB$fhlfj?aj_?K=e8?Cu{cz69#7*@odi~&lxRe#Xj4EG=^_M)
z7B&^pH~J9-L=h2Tl1B+Z8F~~Eb%1mukrIhU1&Blhy7fkt^++huHv)i1pA=aN5m|85
z4tTayTg6)MuwMTLO(X|v@@Gx$H4l>zP7GE?48$lswK_4Thwm^|Iv_idB29US3BhED
z`X(jm@dyh5RAV(m-mq5N14-FXFRhh+QPWC-!v%HN0@u|4h^VMms;7z!1~|zFdP}E%
zji`u<0R?>)O7D?PYy@q^1Sz?giloF46D3(Y*dZ?949bBr@^l2wPyx!&NsD0u(m0LO
zSdG?rjo6rtA^=m|$c=y3jc~vo?qpCnG-1O*jtC`EH3p8}_zB{ei&nype#THEg;S?x
zQFI_x>=asERTFqnj9GJv>_7t_MN)r|UgofB{>BQvcv^l#kou?u_Q;M46?IZYTfy>I
zR3dd?g-Xx%Q<9=6qr_GT`H)NncrAr`k{FTdMNk#_cWcm3QPppZh=~KKet`9dC5Kj>
zc#_vJO9}}NGL&UA#COFsB`m30E*V$IcvbAzD}6}+MuA9^!z6GunGODENe*_2{U~U8
zsEDHs2;~FP~Ez?zCNJ>8dQy$_$
zQx}M1gN2Ul#Z4Z$i*NTej|OSKmLPU1B1ABKB!qG0Qia#^N<
zX@rh+#8LLir&Qn|8Ri+@r7$uVgTM9v74`L?a03U4s(Y`&Ev%tD+`*!bN_jk^8HU1i
zcPLIYMvIqfi+AOfM)N_(6R2q_8wGM5$kQ#anqNOx9RLQYx#40q1*IwDiGf90oOBPs
zN|auS1Z~oS{Sj=1DjRSXs796`5Yr<;qhV-Dc@ASCIO0aK0&poKtZkW^gS6HO`JFk$^?fM
z#Csj|tt~rdC)-<&_FFgdBW)J{C*8NQUFvveMi2;45LcUBJTekIOAs=VS%U+a5BZiT
zI$`sORv1!1fe@tOGg&dUZ{VG0hjbxv
z0B;*69pfyX7H%GMCTD0Ch7z!-W?|OKOH$(n^vQ^5>6x9Hc}GVk8e=8^b1VBLU(LlD
zh?*IaW@!Mzs%K%UcG79ah9?yxYJx&KF(ikwgjGm2HKnMXlO><=HEW@JH@dqfB`xds{)3fQMirKa=on~(Jaf8iLYr^ww
zNi;3@@pk%h!4S7*ZovYXqHTMkV)Pb#;HEJjbDHe}l*;FK!mFotiZ4lX7G-lWlH)t1
zqAC}JdDDTg3{o0C{ADbhJ`1C9sFOOl20S55ng9uiiIs@Y_PHgP@k#e3{R46J!eb1qXnx=AOZn)S1l%36hkugz3pfoKE*k#)}lZ?n=T
zZ9;RN0e5`-Yw$b&rVm46a(8pH(zr+$x*ek*P|1_mfJx?1hs{TuKpQeJBYi-ObKiO=
zJQ5dlkv@Ff7p)SeG^!OSFoH1y!@*O
N)ag#$yt`>_I!b#V41~Xdn^j|Ti?Lae^>_j$RWSZjM@~e6
zX+gKY#KK}#I(7w19+aUk{HJ=O%xUzue8tz%%fO3czCP79xqv7Q%$ZA*FtEc!7%XLZGavBEobHLLB(#qGV2T{S>U678Uk
zf$af?YLU5JQ(aNZ_RBJZ3CUJ-w@GXy%cQ{5S{iEPJfRGqy!F1A%{vA3#9D+Yu%dM
zK#ZGRA5>K98PZx^E@DtZh$0HDNufV6Sh?NHNIgmaGQ6q6WI=ti(mqwdV4;OJ0QLdX?Tve`lJlDRm%u%Dl
zrHMiNbyt_=T=Ppz#j>cv&7CmZ9-B0~18zKbi(T8*Hk1mk_7$$@FpsGM0L?krts#hy
zj7*~xKKOymQiEB*bXR3Wob+2iN9rduGD`Q0*_@s_d4C7(my40E5
z+@dtK)s)P!VoiK9-J6nM;p<;!9G_oO;lnc4kbFjl1->8UKq6xY>H)1BQ3Wu@72&mr
zhK*Wtb=Zjvy+zF18id)|%_eHgos5cN+7aUa>;+8ddfmdbAtD7Ya00FP40q4RbA!DEaTqn!`MZQ5#wEV2!T>Iyaf?n`8Z=v
z)nsGcRLH9{0Iah*Ye(-|m}%VKT7e|d3868}TX^hEo<-#L`#Cv0Q8e^PD
zfHk22DoHw+H5S%f)m1$jI$}A)fq8mT(LyvMF_Q010g(PO2>@wCaOX#Xp&?Oe6hIl6
zMi~$j4KHRVCDV{Z1CQl88y$R@p1u(O{)3_<)MA)ZAmI;sNp+5rFq!QLi*HTpbTp=wjf%SNXS3!LwNB{^m}vl_X%e%Du|}B-Xcs%7y}LeZ
zQ9`eNc!lUYv^ZP~Vt_eQX6F;clR`G>vtDh~?q|(j#|IvPwMGF3z|VPj?Y*Ww&9D!`
zHpWvRZNmd?5KQfINNbpO+7Ju|_U#NZz->(YyWu?F<$=%NhFe0mVB#k3Or(x+{UhaJ
zDsoImm5gBOsA$DIlM(z9g3NCJ_C{vrWLxcCZ$ArdfjB(5OgQtFuP@lYrfqNkhDm?$
zhJ=M}lW`EFaHgpcWjj2$Z%c3WHtjex=l_oITDXk(+J&s+R;kc%FEP?GQ4L!Qji|gs
z(GJHWNa|w-aAf|_0k@o5OKvm}yul6-0v}#BbwcEFjQJLj4N&JcZSnkeO3j?`PVf&1
zKT+le%^QEB3zyRYqAMT&I_zWb497Z21@a&MEs@AvP&SJk{&04-k%d%8DF2c;op3Z~
zZ}1l5ze_J9yuXYdY!78~3o&ynPjlqP^X&ex0H?JUDp}jka})@->z;9^TJ!kUb1om>
z5<88>8*@cZ4;cyWVU*z4O7Z;Ol3wi?;QbJ*=OdS{sU4!zutp*22>fjymixw4F|GKFX3MRdT_`vjC
zm=R(I?_y>$T_fZ{Yp+Qs0VTyT;4KVhzrN3usZ2=$N)e2f^7ee-gU+N+DFPLD&j%o2
zxLoIlZAafyY8FtLE%5MSvIq-x_x3?Xu#5hQepiKuIrn!D_}L0 0:
- foundEvent = self.root.tk.dooneevent(TCL_ALL_EVENTS)
-
- def destroy (self):
- self.root.destroy()
-
-if __name__ == '__main__':
- root = Tix.Tk()
- RunSample(root)
diff --git a/Demo/tix/samples/BtnBox.py b/Demo/tix/samples/BtnBox.py
deleted file mode 100755
index 57d02dfefc..0000000000
--- a/Demo/tix/samples/BtnBox.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidgets.py": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program.
-
-# This file demonstrates the use of the tixButtonBox widget, which is a
-# group of TK buttons. You can use it to manage the buttons in a dialog box,
-# for example.
-#
-
-import Tix
-
-def RunSample(w):
- # Create the label on the top of the dialog box
- #
- top = Tix.Label(w, padx=20, pady=10, bd=1, relief=Tix.RAISED,
- anchor=Tix.CENTER, text='This dialog box is\n a demonstration of the\n tixButtonBox widget')
-
- # Create the button box and add a few buttons in it. Set the
- # -width of all the buttons to the same value so that they
- # appear in the same size.
- #
- # Note that the -text, -underline, -command and -width options are all
- # standard options of the button widgets.
- #
- box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
- box.add('ok', text='OK', underline=0, width=5,
- command=lambda w=w: w.destroy())
- box.add('close', text='Cancel', underline=0, width=5,
- command=lambda w=w: w.destroy())
- box.pack(side=Tix.BOTTOM, fill=Tix.X)
- top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
-
-if __name__ == '__main__':
- root = Tix.Tk()
- RunSample(root)
- root.mainloop()
diff --git a/Demo/tix/samples/CmpImg.py b/Demo/tix/samples/CmpImg.py
deleted file mode 100755
index 4e08df799b..0000000000
--- a/Demo/tix/samples/CmpImg.py
+++ /dev/null
@@ -1,197 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidgets.py": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program.
-
-# This file demonstrates the use of the compound images: it uses compound
-# images to display a text string together with a pixmap inside
-# buttons
-#
-
-import Tix
-
-network_pixmap = """/* XPM */
-static char * netw_xpm[] = {
-/* width height ncolors chars_per_pixel */
-"32 32 7 1",
-/* colors */
-" s None c None",
-". c #000000000000",
-"X c white",
-"o c #c000c000c000",
-"O c #404040",
-"+ c blue",
-"@ c red",
-/* pixels */
-" ",
-" .............. ",
-" .XXXXXXXXXXXX. ",
-" .XooooooooooO. ",
-" .Xo.......XoO. ",
-" .Xo.++++o+XoO. ",
-" .Xo.++++o+XoO. ",
-" .Xo.++oo++XoO. ",
-" .Xo.++++++XoO. ",
-" .Xo.+o++++XoO. ",
-" .Xo.++++++XoO. ",
-" .Xo.XXXXXXXoO. ",
-" .XooooooooooO. ",
-" .Xo@ooo....oO. ",
-" .............. .XooooooooooO. ",
-" .XXXXXXXXXXXX. .XooooooooooO. ",
-" .XooooooooooO. .OOOOOOOOOOOO. ",
-" .Xo.......XoO. .............. ",
-" .Xo.++++o+XoO. @ ",
-" .Xo.++++o+XoO. @ ",
-" .Xo.++oo++XoO. @ ",
-" .Xo.++++++XoO. @ ",
-" .Xo.+o++++XoO. @ ",
-" .Xo.++++++XoO. ..... ",
-" .Xo.XXXXXXXoO. .XXX. ",
-" .XooooooooooO.@@@@@@.X O. ",
-" .Xo@ooo....oO. .OOO. ",
-" .XooooooooooO. ..... ",
-" .XooooooooooO. ",
-" .OOOOOOOOOOOO. ",
-" .............. ",
-" "};
-"""
-
-hard_disk_pixmap = """/* XPM */
-static char * drivea_xpm[] = {
-/* width height ncolors chars_per_pixel */
-"32 32 5 1",
-/* colors */
-" s None c None",
-". c #000000000000",
-"X c white",
-"o c #c000c000c000",
-"O c #800080008000",
-/* pixels */
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" .......................... ",
-" .XXXXXXXXXXXXXXXXXXXXXXXo. ",
-" .XooooooooooooooooooooooO. ",
-" .Xooooooooooooooooo..oooO. ",
-" .Xooooooooooooooooo..oooO. ",
-" .XooooooooooooooooooooooO. ",
-" .Xoooooooo.......oooooooO. ",
-" .Xoo...................oO. ",
-" .Xoooooooo.......oooooooO. ",
-" .XooooooooooooooooooooooO. ",
-" .XooooooooooooooooooooooO. ",
-" .XooooooooooooooooooooooO. ",
-" .XooooooooooooooooooooooO. ",
-" .oOOOOOOOOOOOOOOOOOOOOOOO. ",
-" .......................... ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" ",
-" "};
-"""
-
-network_bitmap = """
-#define netw_width 32
-#define netw_height 32
-static unsigned char netw_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0x02, 0x40,
- 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x52,
- 0x00, 0x00, 0x0a, 0x52, 0x00, 0x00, 0x8a, 0x51, 0x00, 0x00, 0x0a, 0x50,
- 0x00, 0x00, 0x4a, 0x50, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x50,
- 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x02, 0x40, 0xfe, 0x7f, 0x52, 0x55,
- 0x02, 0x40, 0xaa, 0x6a, 0xfa, 0x5f, 0xfe, 0x7f, 0x0a, 0x50, 0xfe, 0x7f,
- 0x0a, 0x52, 0x80, 0x00, 0x0a, 0x52, 0x80, 0x00, 0x8a, 0x51, 0x80, 0x00,
- 0x0a, 0x50, 0x80, 0x00, 0x4a, 0x50, 0x80, 0x00, 0x0a, 0x50, 0xe0, 0x03,
- 0x0a, 0x50, 0x20, 0x02, 0xfa, 0xdf, 0x3f, 0x03, 0x02, 0x40, 0xa0, 0x02,
- 0x52, 0x55, 0xe0, 0x03, 0xaa, 0x6a, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00,
- 0xfe, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-"""
-
-hard_disk_bitmap = """
-#define drivea_width 32
-#define drivea_height 32
-static unsigned char drivea_bits[] = {
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0xf8, 0xff, 0xff, 0x1f, 0x08, 0x00, 0x00, 0x18, 0xa8, 0xaa, 0xaa, 0x1a,
- 0x48, 0x55, 0xd5, 0x1d, 0xa8, 0xaa, 0xaa, 0x1b, 0x48, 0x55, 0x55, 0x1d,
- 0xa8, 0xfa, 0xaf, 0x1a, 0xc8, 0xff, 0xff, 0x1d, 0xa8, 0xfa, 0xaf, 0x1a,
- 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xaa, 0xaa, 0x1a, 0x48, 0x55, 0x55, 0x1d,
- 0xa8, 0xaa, 0xaa, 0x1a, 0xf8, 0xff, 0xff, 0x1f, 0xf8, 0xff, 0xff, 0x1f,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-"""
-
-def RunSample(w):
- w.img0 = Tix.Image('pixmap', data=network_pixmap)
- if not w.img0:
- w.img0 = Tix.Image('bitmap', data=network_bitmap)
- w.img1 = Tix.Image('pixmap', data=hard_disk_pixmap)
- if not w.img0:
- w.img1 = Tix.Image('bitmap', data=hard_disk_bitmap)
-
- hdd = Tix.Button(w, padx=4, pady=1, width=120)
- net = Tix.Button(w, padx=4, pady=1, width=120)
-
- # Create the first image: we create a line, then put a string,
- # a space and a image into this line, from left to right.
- # The result: we have a one-line image that consists of three
- # individual items
- #
- # The tk.calls should be methods in Tix ...
- w.hdd_img = Tix.Image('compound', window=hdd)
- w.hdd_img.tk.call(str(w.hdd_img), 'add', 'line')
- w.hdd_img.tk.call(str(w.hdd_img), 'add', 'text', '-text', 'Hard Disk',
- '-underline', '0')
- w.hdd_img.tk.call(str(w.hdd_img), 'add', 'space', '-width', '7')
- w.hdd_img.tk.call(str(w.hdd_img), 'add', 'image', '-image', w.img1)
-
- # Put this image into the first button
- #
- hdd['image'] = w.hdd_img
-
- # Next button
- w.net_img = Tix.Image('compound', window=net)
- w.net_img.tk.call(str(w.net_img), 'add', 'line')
- w.net_img.tk.call(str(w.net_img), 'add', 'text', '-text', 'Network',
- '-underline', '0')
- w.net_img.tk.call(str(w.net_img), 'add', 'space', '-width', '7')
- w.net_img.tk.call(str(w.net_img), 'add', 'image', '-image', w.img0)
-
- # Put this image into the first button
- #
- net['image'] = w.net_img
-
- close = Tix.Button(w, pady=1, text='Close',
- command=lambda w=w: w.destroy())
-
- hdd.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1)
- net.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1)
- close.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1)
-
-if __name__ == '__main__':
- root = Tix.Tk()
- RunSample(root)
- root.mainloop()
-
diff --git a/Demo/tix/samples/ComboBox.py b/Demo/tix/samples/ComboBox.py
deleted file mode 100755
index afecea4c7d..0000000000
--- a/Demo/tix/samples/ComboBox.py
+++ /dev/null
@@ -1,102 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidgets.py": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program.
-
-# This file demonstrates the use of the tixComboBox widget, which is close
-# to the MS Window Combo Box control.
-#
-import Tix
-
-def RunSample(w):
- global demo_month, demo_year
-
- top = Tix.Frame(w, bd=1, relief=Tix.RAISED)
-
- demo_month = Tix.StringVar()
- demo_year = Tix.StringVar()
-
- # $w.top.a is a drop-down combo box. It is not editable -- who wants
- # to invent new months?
- #
- # [Hint] The -options switch sets the options of the subwidgets.
- # [Hint] We set the label.width subwidget option of both comboboxes to
- # be 10 so that their labels appear to be aligned.
- #
- a = Tix.ComboBox(top, label="Month: ", dropdown=1,
- command=select_month, editable=0, variable=demo_month,
- options='listbox.height 6 label.width 10 label.anchor e')
-
- # $w.top.b is a non-drop-down combo box. It is not editable: we provide
- # four choices for the user, but he can enter an alternative year if he
- # wants to.
- #
- # [Hint] Use the padY and anchor options of the label subwidget to
- # align the label with the entry subwidget.
- # [Hint] Notice that you should use padY (the NAME of the option) and not
- # pady (the SWITCH of the option).
- #
- b = Tix.ComboBox(top, label="Year: ", dropdown=0,
- command=select_year, editable=1, variable=demo_year,
- options='listbox.height 4 label.padY 5 label.width 10 label.anchor ne')
-
- a.pack(side=Tix.TOP, anchor=Tix.W)
- b.pack(side=Tix.TOP, anchor=Tix.W)
-
- a.insert(Tix.END, 'January')
- a.insert(Tix.END, 'February')
- a.insert(Tix.END, 'March')
- a.insert(Tix.END, 'April')
- a.insert(Tix.END, 'May')
- a.insert(Tix.END, 'June')
- a.insert(Tix.END, 'July')
- a.insert(Tix.END, 'August')
- a.insert(Tix.END, 'September')
- a.insert(Tix.END, 'October')
- a.insert(Tix.END, 'November')
- a.insert(Tix.END, 'December')
-
- b.insert(Tix.END, '1992')
- b.insert(Tix.END, '1993')
- b.insert(Tix.END, '1994')
- b.insert(Tix.END, '1995')
- b.insert(Tix.END, '1996')
-
- # Use "tixSetSilent" to set the values of the combo box if you
- # don't want your -command procedures (cbx:select_month and
- # cbx:select_year) to be called.
- #
- a.set_silent('January')
- b.set_silent('1995')
-
- box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
- box.add('ok', text='Ok', underline=0, width=6,
- command=lambda w=w: ok_command(w))
- box.add('cancel', text='Cancel', underline=0, width=6,
- command=lambda w=w: w.destroy())
- box.pack(side=Tix.BOTTOM, fill=Tix.X)
- top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
-
-def select_month(event=None):
- # tixDemo:Status "Month = %s" % demo_month.get()
- pass
-
-def select_year(event=None):
- # tixDemo:Status "Year = %s" % demo_year.get()
- pass
-
-def ok_command(w):
- # tixDemo:Status "Month = %s, Year= %s" % (demo_month.get(), demo_year.get())
- w.destroy()
-
-if __name__ == '__main__':
- root = Tix.Tk()
- RunSample(root)
- root.mainloop()
diff --git a/Demo/tix/samples/Control.py b/Demo/tix/samples/Control.py
deleted file mode 100755
index e85ee845df..0000000000
--- a/Demo/tix/samples/Control.py
+++ /dev/null
@@ -1,122 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidgets.py": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program.
-
-# This file demonstrates the use of the tixControl widget -- it is an
-# entry widget with up/down arrow buttons. You can use the arrow buttons
-# to adjust the value inside the entry widget.
-#
-# This example program uses three Control widgets. One lets you select
-# integer values; one lets you select floating point values and the last
-# one lets you select a few names.
-
-import Tix
-
-TCL_ALL_EVENTS = 0
-
-def RunSample (root):
- control = DemoControl(root)
- control.mainloop()
- control.destroy()
-
-class DemoControl:
- def __init__(self, w):
- self.root = w
- self.exit = -1
-
- global demo_maker, demo_thrust, demo_num_engines
-
- demo_maker = Tix.StringVar()
- demo_thrust = Tix.DoubleVar()
- demo_num_engines = Tix.IntVar()
- demo_maker.set('P&W')
- demo_thrust.set(20000.0)
- demo_num_engines.set(2)
-
- top = Tix.Frame(w, bd=1, relief=Tix.RAISED)
-
- # $w.top.a allows only integer values
- #
- # [Hint] The -options switch sets the options of the subwidgets.
- # [Hint] We set the label.width subwidget option of the Controls to
- # be 16 so that their labels appear to be aligned.
- #
- a = Tix.Control(top, label='Number of Engines: ', integer=1,
- variable=demo_num_engines, min=1, max=4,
- options='entry.width 10 label.width 20 label.anchor e')
-
- b = Tix.Control(top, label='Thrust: ', integer=0,
- min='10000.0', max='60000.0', step=500,
- variable=demo_thrust,
- options='entry.width 10 label.width 20 label.anchor e')
-
- c = Tix.Control(top, label='Engine Maker: ', value='P&W',
- variable=demo_maker,
- options='entry.width 10 label.width 20 label.anchor e')
-
- # We can't define these in the init because the widget 'c' doesn't
- # exist yet and we need to reference it
- c['incrcmd'] = lambda w=c: adjust_maker(w, 1)
- c['decrcmd'] = lambda w=c: adjust_maker(w, -1)
- c['validatecmd'] = lambda w=c: validate_maker(w)
-
- a.pack(side=Tix.TOP, anchor=Tix.W)
- b.pack(side=Tix.TOP, anchor=Tix.W)
- c.pack(side=Tix.TOP, anchor=Tix.W)
-
- box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
- box.add('ok', text='Ok', underline=0, width=6,
- command=self.okcmd)
- box.add('cancel', text='Cancel', underline=0, width=6,
- command=self.quitcmd)
- box.pack(side=Tix.BOTTOM, fill=Tix.X)
- top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
-
- def okcmd (self):
- # tixDemo:Status "Selected %d of %s engines each of thrust %d", (demo_num_engines.get(), demo_maker.get(), demo_thrust.get())
- self.quitcmd()
-
- def quitcmd (self):
- self.exit = 0
-
- def mainloop(self):
- while self.exit < 0:
- self.root.tk.dooneevent(TCL_ALL_EVENTS)
-
- def destroy (self):
- self.root.destroy()
-
-maker_list = ['P&W', 'GE', 'Rolls Royce']
-
-def adjust_maker(w, inc):
- i = maker_list.index(demo_maker.get())
- i = i + inc
- if i >= len(maker_list):
- i = 0
- elif i < 0:
- i = len(maker_list) - 1
-
- # In Tcl/Tix we should return the string maker_list[i]. We can't
- # do that in Tkinter so we set the global variable. (This works).
- demo_maker.set(maker_list[i])
-
-def validate_maker(w):
- try:
- i = maker_list.index(demo_maker.get())
- except ValueError:
- # Works here though. Why ? Beats me.
- return maker_list[0]
- # Works here though. Why ? Beats me.
- return maker_list[i]
-
-if __name__ == '__main__':
- root = Tix.Tk()
- RunSample(root)
diff --git a/Demo/tix/samples/DirList.py b/Demo/tix/samples/DirList.py
deleted file mode 100755
index b2aad336fc..0000000000
--- a/Demo/tix/samples/DirList.py
+++ /dev/null
@@ -1,132 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidgets.py": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program using tixwish.
-
-# This file demonstrates the use of the tixDirList widget -- you can
-# use it for the user to select a directory. For example, an installation
-# program can use the tixDirList widget to ask the user to select the
-# installation directory for an application.
-#
-
-import Tix, os, copy
-from Tkconstants import *
-
-TCL_ALL_EVENTS = 0
-
-def RunSample (root):
- dirlist = DemoDirList(root)
- dirlist.mainloop()
- dirlist.destroy()
-
-class DemoDirList:
- def __init__(self, w):
- self.root = w
- self.exit = -1
-
- z = w.winfo_toplevel()
- z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
-
- # Create the tixDirList and the tixLabelEntry widgets on the on the top
- # of the dialog box
-
- # bg = root.tk.eval('tix option get bg')
- # adding bg=bg crashes Windows pythonw tk8.3.3 Python 2.1.0
-
- top = Tix.Frame( w, relief=RAISED, bd=1)
-
- # Create the DirList widget. By default it will show the current
- # directory
- #
- #
- top.dir = Tix.DirList(top)
- top.dir.hlist['width'] = 40
-
- # When the user presses the ".." button, the selected directory
- # is "transferred" into the entry widget
- #
- top.btn = Tix.Button(top, text = " >> ", pady = 0)
-
- # We use a LabelEntry to hold the installation directory. The user
- # can choose from the DirList widget, or he can type in the directory
- # manually
- #
- top.ent = Tix.LabelEntry(top, label="Installation Directory:",
- labelside = 'top',
- options = '''
- entry.width 40
- label.anchor w
- ''')
-
- font = self.root.tk.eval('tix option get fixed_font')
- # font = self.root.master.tix_option_get('fixed_font')
- top.ent.entry['font'] = font
-
- self.dlist_dir = copy.copy(os.curdir)
- # This should work setting the entry's textvariable
- top.ent.entry['textvariable'] = self.dlist_dir
- top.btn['command'] = lambda dir=top.dir, ent=top.ent, self=self: \
- self.copy_name(dir,ent)
-
- # top.ent.entry.insert(0,'tix'+`self`)
- top.ent.entry.bind('', lambda self=self: self.okcmd () )
-
- top.pack( expand='yes', fill='both', side=TOP)
- top.dir.pack( expand=1, fill=BOTH, padx=4, pady=4, side=LEFT)
- top.btn.pack( anchor='s', padx=4, pady=4, side=LEFT)
- top.ent.pack( expand=1, fill=X, anchor='s', padx=4, pady=4, side=LEFT)
-
- # Use a ButtonBox to hold the buttons.
- #
- box = Tix.ButtonBox (w, orientation='horizontal')
- box.add ('ok', text='Ok', underline=0, width=6,
- command = lambda self=self: self.okcmd () )
- box.add ('cancel', text='Cancel', underline=0, width=6,
- command = lambda self=self: self.quitcmd () )
-
- box.pack( anchor='s', fill='x', side=BOTTOM)
-
- def copy_name (self, dir, ent):
- # This should work as it is the entry's textvariable
- self.dlist_dir = dir.cget('value')
- # but it isn't so I'll do it manually
- ent.entry.delete(0,'end')
- ent.entry.insert(0, self.dlist_dir)
-
- def okcmd (self):
- # tixDemo:Status "You have selected the directory" + self.dlist_dir
- self.quitcmd()
-
- def quitcmd (self):
- self.exit = 0
-
- def mainloop(self):
- while self.exit < 0:
- self.root.tk.dooneevent(TCL_ALL_EVENTS)
-
- def destroy (self):
- self.root.destroy()
-
-# This "if" statement makes it possible to run this script file inside or
-# outside of the main demo program "tixwidgets.py".
-#
-if __name__== '__main__' :
- import tkMessageBox, traceback
-
- try:
- root=Tix.Tk()
- RunSample(root)
- except:
- t, v, tb = sys.exc_info()
- text = "Error running the demo script:\n"
- for line in traceback.format_exception(t,v,tb):
- text = text + line + '\n'
- d = tkMessageBox.showerror ( 'Tix Demo Error', text)
-
diff --git a/Demo/tix/samples/DirTree.py b/Demo/tix/samples/DirTree.py
deleted file mode 100755
index d007a2ba72..0000000000
--- a/Demo/tix/samples/DirTree.py
+++ /dev/null
@@ -1,118 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidgets.py": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program using tixwish.
-
-# This file demonstrates the use of the tixDirTree widget -- you can
-# use it for the user to select a directory. For example, an installation
-# program can use the tixDirTree widget to ask the user to select the
-# installation directory for an application.
-#
-
-import Tix, os, copy
-from Tkconstants import *
-
-TCL_ALL_EVENTS = 0
-
-def RunSample (root):
- dirtree = DemoDirTree(root)
- dirtree.mainloop()
- dirtree.destroy()
-
-class DemoDirTree:
- def __init__(self, w):
- self.root = w
- self.exit = -1
-
- z = w.winfo_toplevel()
- z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
-
- # Create the tixDirTree and the tixLabelEntry widgets on the on the top
- # of the dialog box
-
- # bg = root.tk.eval('tix option get bg')
- # adding bg=bg crashes Windows pythonw tk8.3.3 Python 2.1.0
-
- top = Tix.Frame( w, relief=RAISED, bd=1)
-
- # Create the DirTree widget. By default it will show the current
- # directory
- #
- #
- top.dir = Tix.DirTree(top)
- top.dir.hlist['width'] = 40
-
- # When the user presses the ".." button, the selected directory
- # is "transferred" into the entry widget
- #
- top.btn = Tix.Button(top, text = " >> ", pady = 0)
-
- # We use a LabelEntry to hold the installation directory. The user
- # can choose from the DirTree widget, or he can type in the directory
- # manually
- #
- top.ent = Tix.LabelEntry(top, label="Installation Directory:",
- labelside = 'top',
- options = '''
- entry.width 40
- label.anchor w
- ''')
-
- self.dlist_dir = copy.copy(os.curdir)
- top.ent.entry['textvariable'] = self.dlist_dir
- top.btn['command'] = lambda dir=top.dir, ent=top.ent, self=self: \
- self.copy_name(dir,ent)
-
- top.ent.entry.bind('', lambda self=self: self.okcmd () )
-
- top.pack( expand='yes', fill='both', side=TOP)
- top.dir.pack( expand=1, fill=BOTH, padx=4, pady=4, side=LEFT)
- top.btn.pack( anchor='s', padx=4, pady=4, side=LEFT)
- top.ent.pack( expand=1, fill=X, anchor='s', padx=4, pady=4, side=LEFT)
-
- # Use a ButtonBox to hold the buttons.
- #
- box = Tix.ButtonBox (w, orientation='horizontal')
- box.add ('ok', text='Ok', underline=0, width=6,
- command = lambda self=self: self.okcmd () )
- box.add ('cancel', text='Cancel', underline=0, width=6,
- command = lambda self=self: self.quitcmd () )
-
- box.pack( anchor='s', fill='x', side=BOTTOM)
-
- def copy_name (self, dir, ent):
- # This should work as it is the entry's textvariable
- self.dlist_dir = dir.cget('value')
- # but it isn't so I'll do it manually
- ent.entry.delete(0,'end')
- ent.entry.insert(0, self.dlist_dir)
-
- def okcmd (self):
- # tixDemo:Status "You have selected the directory" + self.dlist_dir
- self.quitcmd()
-
- def quitcmd (self):
- # tixDemo:Status "You have selected the directory" + self.dlist_dir
- self.exit = 0
-
- def mainloop(self):
- while self.exit < 0:
- self.root.tk.dooneevent(TCL_ALL_EVENTS)
-
- def destroy (self):
- self.root.destroy()
-
-# This "if" statement makes it possible to run this script file inside or
-# outside of the main demo program "tixwidgets.py".
-#
-if __name__== '__main__' :
- root=Tix.Tk()
- RunSample(root)
-
diff --git a/Demo/tix/samples/NoteBook.py b/Demo/tix/samples/NoteBook.py
deleted file mode 100755
index abf3bfd954..0000000000
--- a/Demo/tix/samples/NoteBook.py
+++ /dev/null
@@ -1,119 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidgets.py": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program.
-
-# This file demonstrates the use of the tixNoteBook widget, which allows
-# you to lay out your interface using a "notebook" metaphore
-#
-import Tix
-
-def RunSample(w):
- global root
- root = w
-
- # We use these options to set the sizes of the subwidgets inside the
- # notebook, so that they are well-aligned on the screen.
- prefix = Tix.OptionName(w)
- if prefix:
- prefix = '*'+prefix
- else:
- prefix = ''
- w.option_add(prefix+'*TixControl*entry.width', 10)
- w.option_add(prefix+'*TixControl*label.width', 18)
- w.option_add(prefix+'*TixControl*label.anchor', Tix.E)
- w.option_add(prefix+'*TixNoteBook*tagPadX', 8)
-
- # Create the notebook widget and set its backpagecolor to gray.
- # Note that the -backpagecolor option belongs to the "nbframe"
- # subwidget.
- nb = Tix.NoteBook(w, name='nb', ipadx=6, ipady=6)
- nb['bg'] = 'gray'
- nb.nbframe['backpagecolor'] = 'gray'
-
- # Create the two tabs on the notebook. The -underline option
- # puts a underline on the first character of the labels of the tabs.
- # Keyboard accelerators will be defined automatically according
- # to the underlined character.
- nb.add('hard_disk', label="Hard Disk", underline=0)
- nb.add('network', label="Network", underline=0)
-
- nb.pack(expand=1, fill=Tix.BOTH, padx=5, pady=5 ,side=Tix.TOP)
-
- #----------------------------------------
- # Create the first page
- #----------------------------------------
- # Create two frames: one for the common buttons, one for the
- # other widgets
- #
- tab=nb.hard_disk
- f = Tix.Frame(tab)
- common = Tix.Frame(tab)
-
- f.pack(side=Tix.LEFT, padx=2, pady=2, fill=Tix.BOTH, expand=1)
- common.pack(side=Tix.RIGHT, padx=2, fill=Tix.Y)
-
- a = Tix.Control(f, value=12, label='Access time: ')
- w = Tix.Control(f, value=400, label='Write Throughput: ')
- r = Tix.Control(f, value=400, label='Read Throughput: ')
- c = Tix.Control(f, value=1021, label='Capacity: ')
-
- a.pack(side=Tix.TOP, padx=20, pady=2)
- w.pack(side=Tix.TOP, padx=20, pady=2)
- r.pack(side=Tix.TOP, padx=20, pady=2)
- c.pack(side=Tix.TOP, padx=20, pady=2)
-
- # Create the common buttons
- createCommonButtons(common)
-
- #----------------------------------------
- # Create the second page
- #----------------------------------------
-
- tab = nb.network
-
- f = Tix.Frame(tab)
- common = Tix.Frame(tab)
-
- f.pack(side=Tix.LEFT, padx=2, pady=2, fill=Tix.BOTH, expand=1)
- common.pack(side=Tix.RIGHT, padx=2, fill=Tix.Y)
-
- a = Tix.Control(f, value=12, label='Access time: ')
- w = Tix.Control(f, value=400, label='Write Throughput: ')
- r = Tix.Control(f, value=400, label='Read Throughput: ')
- c = Tix.Control(f, value=1021, label='Capacity: ')
- u = Tix.Control(f, value=10, label='Users: ')
-
- a.pack(side=Tix.TOP, padx=20, pady=2)
- w.pack(side=Tix.TOP, padx=20, pady=2)
- r.pack(side=Tix.TOP, padx=20, pady=2)
- c.pack(side=Tix.TOP, padx=20, pady=2)
- u.pack(side=Tix.TOP, padx=20, pady=2)
-
- createCommonButtons(common)
-
-def doDestroy():
- global root
- root.destroy()
-
-def createCommonButtons(master):
- ok = Tix.Button(master, name='ok', text='OK', width=6,
- command=doDestroy)
- cancel = Tix.Button(master, name='cancel',
- text='Cancel', width=6,
- command=doDestroy)
-
- ok.pack(side=Tix.TOP, padx=2, pady=2)
- cancel.pack(side=Tix.TOP, padx=2, pady=2)
-
-if __name__ == '__main__':
- root = Tix.Tk()
- RunSample(root)
- root.mainloop()
diff --git a/Demo/tix/samples/OptMenu.py b/Demo/tix/samples/OptMenu.py
deleted file mode 100755
index ecb0c86abc..0000000000
--- a/Demo/tix/samples/OptMenu.py
+++ /dev/null
@@ -1,68 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidgets.py": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program.
-
-# This file demonstrates the use of the tixOptionMenu widget -- you can
-# use it for the user to choose from a fixed set of options
-#
-import Tix
-
-options = {'text':'Plain Text', 'post':'PostScript', 'html':'HTML',
- 'tex':'LaTeX', 'rtf':'Rich Text Format'}
-
-def RunSample(w):
- global demo_opt_from, demo_opt_to
-
- demo_opt_from = Tix.StringVar()
- demo_opt_to = Tix.StringVar()
-
- top = Tix.Frame(w, bd=1, relief=Tix.RAISED)
-
- from_file = Tix.OptionMenu(top, label="From File Format : ",
- variable=demo_opt_from,
- options = 'label.width 19 label.anchor e menubutton.width 15')
-
- to_file = Tix.OptionMenu(top, label="To File Format : ",
- variable=demo_opt_to,
- options='label.width 19 label.anchor e menubutton.width 15')
-
- # Add the available options to the two OptionMenu widgets
- #
- # [Hint] You have to add the options first before you set the
- # global variables "demo_opt_from" and "demo_opt_to". Otherwise
- # the OptionMenu widget will complain about "unknown options"!
- #
- for opt in options.keys():
- from_file.add_command(opt, label=options[opt])
- to_file.add_command(opt, label=options[opt])
-
- demo_opt_from.set('html')
- demo_opt_to.set('post')
-
- from_file.pack(side=Tix.TOP, anchor=Tix.W, pady=3, padx=6)
- to_file.pack(side=Tix.TOP, anchor=Tix.W, pady=3, padx=6)
-
- box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
- box.add('ok', text='Ok', underline=0, width=6,
- command=lambda w=w: ok_command(w))
- box.add('cancel', text='Cancel', underline=0, width=6,
- command=lambda w=w: w.destroy())
- box.pack(side=Tix.BOTTOM, fill=Tix.X)
- top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
-
-def ok_command(w):
- # tixDemo:Status "Convert file from %s to %s" % ( demo_opt_from.get(), demo_opt_to.get())
- w.destroy()
-
-if __name__ == '__main__':
- root = Tix.Tk()
- RunSample(root)
- root.mainloop()
diff --git a/Demo/tix/samples/PanedWin.py b/Demo/tix/samples/PanedWin.py
deleted file mode 100755
index bfe10c2736..0000000000
--- a/Demo/tix/samples/PanedWin.py
+++ /dev/null
@@ -1,98 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidgets.py": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program.
-
-# This file demonstrates the use of the tixPanedWindow widget. This program
-# is a dummy news reader: the user can adjust the sizes of the list
-# of artical names and the size of the text widget that shows the body
-# of the article.
-
-import Tix
-
-TCL_ALL_EVENTS = 0
-
-def RunSample (root):
- panedwin = DemoPanedwin(root)
- panedwin.mainloop()
- panedwin.destroy()
-
-class DemoPanedwin:
- def __init__(self, w):
- self.root = w
- self.exit = -1
-
- z = w.winfo_toplevel()
- z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
-
- group = Tix.LabelEntry(w, label='Newsgroup:', options='entry.width 25')
- group.entry.insert(0,'comp.lang.python')
- pane = Tix.PanedWindow(w, orientation='vertical')
-
- p1 = pane.add('list', min=70, size=100)
- p2 = pane.add('text', min=70)
- list = Tix.ScrolledListBox(p1)
- list.listbox['width'] = 80
- list.listbox['height'] = 5
- text = Tix.ScrolledText(p2)
- text.text['width'] = 80
- text.text['height'] = 20
-
- list.listbox.insert(Tix.END, " 12324 Re: Tkinter is good for your health")
- list.listbox.insert(Tix.END, "+ 12325 Re: Tkinter is good for your health")
- list.listbox.insert(Tix.END, "+ 12326 Re: Tix is even better for your health (Was: Tkinter is good...)")
- list.listbox.insert(Tix.END, " 12327 Re: Tix is even better for your health (Was: Tkinter is good...)")
- list.listbox.insert(Tix.END, "+ 12328 Re: Tix is even better for your health (Was: Tkinter is good...)")
- list.listbox.insert(Tix.END, " 12329 Re: Tix is even better for your health (Was: Tkinter is good...)")
- list.listbox.insert(Tix.END, "+ 12330 Re: Tix is even better for your health (Was: Tkinter is good...)")
-
- text.text['bg'] = list.listbox['bg']
- text.text['wrap'] = 'none'
- text.text.insert(Tix.END, """
- Mon, 19 Jun 1995 11:39:52 comp.lang.python Thread 34 of 220
- Lines 353 A new way to put text and bitmaps together iNo responses
- ioi@blue.seas.upenn.edu Ioi K. Lam at University of Pennsylvania
-
- Hi,
-
- I have implemented a new image type called "compound". It allows you
- to glue together a bunch of bitmaps, images and text strings together
- to form a bigger image. Then you can use this image with widgets that
- support the -image option. For example, you can display a text string string
- together with a bitmap, at the same time, inside a TK button widget.
- """)
- text.text['state'] = 'disabled'
-
- list.pack(expand=1, fill=Tix.BOTH, padx=4, pady=6)
- text.pack(expand=1, fill=Tix.BOTH, padx=4, pady=6)
-
- group.pack(side=Tix.TOP, padx=3, pady=3, fill=Tix.BOTH)
- pane.pack(side=Tix.TOP, padx=3, pady=3, fill=Tix.BOTH, expand=1)
-
- box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
- box.add('ok', text='Ok', underline=0, width=6,
- command=self.quitcmd)
- box.add('cancel', text='Cancel', underline=0, width=6,
- command=self.quitcmd)
- box.pack(side=Tix.BOTTOM, fill=Tix.X)
-
- def quitcmd (self):
- self.exit = 0
-
- def mainloop(self):
- while self.exit < 0:
- self.root.tk.dooneevent(TCL_ALL_EVENTS)
-
- def destroy (self):
- self.root.destroy()
-
-if __name__ == '__main__':
- root = Tix.Tk()
- RunSample(root)
diff --git a/Demo/tix/samples/PopMenu.py b/Demo/tix/samples/PopMenu.py
deleted file mode 100755
index 602eafdc5c..0000000000
--- a/Demo/tix/samples/PopMenu.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidgets.py": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program using tixwish.
-
-# This file demonstrates the use of the tixPopupMenu widget.
-#
-import Tix
-
-def RunSample(w):
- # We create the frame and the button, then we'll bind the PopupMenu
- # to both widgets. The result is, when you press the right mouse
- # button over $w.top or $w.top.but, the PopupMenu will come up.
- #
- top = Tix.Frame(w, relief=Tix.RAISED, bd=1)
- but = Tix.Button(top, text='Press the right mouse button over this button or its surrounding area')
- but.pack(expand=1, fill=Tix.BOTH, padx=50, pady=50)
-
- p = Tix.PopupMenu(top, title='Popup Test')
- p.bind_widget(top)
- p.bind_widget(but)
-
- # Set the entries inside the PopupMenu widget.
- # [Hint] You have to manipulate the "menu" subwidget.
- # $w.top.p itself is NOT a menu widget.
- # [Hint] Watch carefully how the sub-menu is created
- #
- p.menu.add_command(label='Desktop', underline=0)
- p.menu.add_command(label='Select', underline=0)
- p.menu.add_command(label='Find', underline=0)
- p.menu.add_command(label='System', underline=1)
- p.menu.add_command(label='Help', underline=0)
- m1 = Tix.Menu(p.menu)
- m1.add_command(label='Hello')
- p.menu.add_cascade(label='More', menu=m1)
-
- but.pack(side=Tix.TOP, padx=40, pady=50)
-
- box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
- box.add('ok', text='Ok', underline=0, width=6,
- command=lambda w=w: w.destroy())
- box.add('cancel', text='Cancel', underline=0, width=6,
- command=lambda w=w: w.destroy())
- box.pack(side=Tix.BOTTOM, fill=Tix.X)
- top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
-
-if __name__ == '__main__':
- root = Tix.Tk()
- RunSample(root)
- root.mainloop()
diff --git a/Demo/tix/samples/SHList1.py b/Demo/tix/samples/SHList1.py
deleted file mode 100755
index 0114dc8a53..0000000000
--- a/Demo/tix/samples/SHList1.py
+++ /dev/null
@@ -1,132 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidgets.py": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program using tixwish.
-
-# This file demonstrates the use of the tixScrolledHList widget.
-#
-
-import Tix
-
-TCL_ALL_EVENTS = 0
-
-def RunSample (root):
- shlist = DemoSHList(root)
- shlist.mainloop()
- shlist.destroy()
-
-class DemoSHList:
- def __init__(self, w):
- self.root = w
- self.exit = -1
-
- z = w.winfo_toplevel()
- z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
-
- # We create the frame and the ScrolledHList widget
- # at the top of the dialog box
- #
- top = Tix.Frame( w, relief=Tix.RAISED, bd=1)
-
- # Put a simple hierachy into the HList (two levels). Use colors and
- # separator widgets (frames) to make the list look fancy
- #
- top.a = Tix.ScrolledHList(top)
- top.a.pack( expand=1, fill=Tix.BOTH, padx=10, pady=10, side=Tix.TOP)
-
- # This is our little relational database
- #
- bosses = [
- ('jeff', 'Jeff Waxman'),
- ('john', 'John Lee'),
- ('peter', 'Peter Kenson')
- ]
-
- employees = [
- ('alex', 'john', 'Alex Kellman'),
- ('alan', 'john', 'Alan Adams'),
- ('andy', 'peter', 'Andreas Crawford'),
- ('doug', 'jeff', 'Douglas Bloom'),
- ('jon', 'peter', 'Jon Baraki'),
- ('chris', 'jeff', 'Chris Geoffrey'),
- ('chuck', 'jeff', 'Chuck McLean')
- ]
-
- hlist=top.a.hlist
-
- # Let configure the appearance of the HList subwidget
- #
- hlist.config( separator='.', width=25, drawbranch=0, indent=10)
-
- count=0
- for boss,name in bosses :
- if count :
- f=Tix.Frame(hlist, name='sep%d' % count, height=2, width=150,
- bd=2, relief=Tix.SUNKEN )
-
- hlist.add_child( itemtype=Tix.WINDOW,
- window=f, state=Tix.DISABLED )
-
- hlist.add(boss, itemtype=Tix.TEXT, text=name)
- count = count+1
-
-
- for person,boss,name in employees :
- # '.' is the separator character we chose above
- #
- key= boss + '.' + person
- # ^^^^ ^^^^^^
- # parent entryPath / child's name
-
- hlist.add( key, text=name )
-
- # [Hint] Make sure the keys (e.g. 'boss.person') you choose
- # are unique names. If you cannot be sure of this (because of
- # the structure of your database, e.g.) you can use the
- # "add_child" command instead:
- #
- # hlist.addchild( boss, text=name)
- # ^^^^
- # parent entryPath
-
-
- # Use a ButtonBox to hold the buttons.
- #
- box= Tix.ButtonBox(top, orientation=Tix.HORIZONTAL )
- box.add( 'ok', text='Ok', underline=0, width=6,
- command = self.okcmd)
-
- box.add( 'cancel', text='Cancel', underline=0, width=6,
- command = self.quitcmd)
-
- box.pack( side=Tix.BOTTOM, fill=Tix.X)
- top.pack( side=Tix.TOP, fill=Tix.BOTH, expand=1 )
-
- def okcmd (self):
- self.quitcmd()
-
- def quitcmd (self):
- self.exit = 0
-
- def mainloop(self):
- while self.exit < 0:
- self.root.tk.dooneevent(TCL_ALL_EVENTS)
-
- def destroy (self):
- self.root.destroy()
-
-
-# This "if" statement makes it possible to run this script file inside or
-# outside of the main demo program "tixwidgets.py".
-#
-if __name__== '__main__' :
- root=Tix.Tk()
- RunSample(root)
-
diff --git a/Demo/tix/samples/SHList2.py b/Demo/tix/samples/SHList2.py
deleted file mode 100755
index e82d1e586a..0000000000
--- a/Demo/tix/samples/SHList2.py
+++ /dev/null
@@ -1,169 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidget": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program using tixwish.
-
-# This file demonstrates how to use multiple columns and multiple styles
-# in the tixHList widget
-#
-# In a tixHList widget, you can have one ore more columns.
-#
-
-import Tix
-
-TCL_ALL_EVENTS = 0
-
-def RunSample (root):
- shlist = DemoSHList(root)
- shlist.mainloop()
- shlist.destroy()
-
-class DemoSHList:
- def __init__(self, w):
- self.root = w
- self.exit = -1
-
- z = w.winfo_toplevel()
- z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
-
- # We create the frame and the ScrolledHList widget
- # at the top of the dialog box
- #
- top = Tix.Frame( w, relief=Tix.RAISED, bd=1)
-
- # Put a simple hierachy into the HList (two levels). Use colors and
- # separator widgets (frames) to make the list look fancy
- #
- top.a = Tix.ScrolledHList(top, options='hlist.columns 3 hlist.header 1' )
- top.a.pack( expand=1, fill=Tix.BOTH, padx=10, pady=10, side=Tix.TOP)
-
- hlist=top.a.hlist
-
- # Create the title for the HList widget
- # >> Notice that we have set the hlist.header subwidget option to true
- # so that the header is displayed
- #
-
- boldfont=hlist.tk.call('tix','option','get','bold_font')
-
- # First some styles for the headers
- style={}
- style['header'] = Tix.DisplayStyle(Tix.TEXT, refwindow=hlist,
- anchor=Tix.CENTER, padx=8, pady=2, font = boldfont )
-
- hlist.header_create(0, itemtype=Tix.TEXT, text='Name',
- style=style['header'])
- hlist.header_create(1, itemtype=Tix.TEXT, text='Position',
- style=style['header'])
-
- # Notice that we use 3 columns in the hlist widget. This way when the user
- # expands the windows wide, the right side of the header doesn't look
- # chopped off. The following line ensures that the 3 column header is
- # not shown unless the hlist window is wider than its contents.
- #
- hlist.column_width(2,0)
-
- # This is our little relational database
- #
- boss = ('doe', 'John Doe', 'Director')
-
- managers = [
- ('jeff', 'Jeff Waxman', 'Manager'),
- ('john', 'John Lee', 'Manager'),
- ('peter', 'Peter Kenson', 'Manager')
- ]
-
- employees = [
- ('alex', 'john', 'Alex Kellman', 'Clerk'),
- ('alan', 'john', 'Alan Adams', 'Clerk'),
- ('andy', 'peter', 'Andreas Crawford', 'Salesman'),
- ('doug', 'jeff', 'Douglas Bloom', 'Clerk'),
- ('jon', 'peter', 'Jon Baraki', 'Salesman'),
- ('chris', 'jeff', 'Chris Geoffrey', 'Clerk'),
- ('chuck', 'jeff', 'Chuck McLean', 'Cleaner')
- ]
-
- style['mgr_name'] = Tix.DisplayStyle(Tix.TEXT, refwindow=hlist)
-
- style['mgr_posn'] = Tix.DisplayStyle(Tix.TEXT, padx=8, refwindow=hlist)
-
- style['empl_name'] = Tix.DisplayStyle(Tix.TEXT, refwindow=hlist)
-
- style['empl_posn'] = Tix.DisplayStyle(Tix.TEXT, padx=8, refwindow=hlist)
-
- # Let configure the appearance of the HList subwidget
- #
- hlist.config(separator='.', width=25, drawbranch=0, indent=10)
- hlist.column_width(0, chars=20)
-
- # Create the boss
- #
- hlist.add ('.', itemtype=Tix.TEXT, text=boss[1],
- style=style['mgr_name'])
- hlist.item_create('.', 1, itemtype=Tix.TEXT, text=boss[2],
- style=style['mgr_posn'])
-
- # Create the managers
- #
-
- for key,name,posn in managers :
- e= '.'+ key
- hlist.add(e, itemtype=Tix.TEXT, text=name,
- style=style['mgr_name'])
- hlist.item_create(e, 1, itemtype=Tix.TEXT, text=posn,
- style=style['mgr_posn'])
-
-
- for key,mgr,name,posn in employees :
- # "." is the separator character we chose above
-
- entrypath = '.' + mgr + '.' + key
-
- # ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
- # parent entryPath / child's name
-
- hlist.add(entrypath, text=name, style=style['empl_name'])
- hlist.item_create(entrypath, 1, itemtype=Tix.TEXT,
- text = posn, style = style['empl_posn'] )
-
-
- # Use a ButtonBox to hold the buttons.
- #
- box= Tix.ButtonBox(top, orientation=Tix.HORIZONTAL )
- box.add( 'ok', text='Ok', underline=0, width=6,
- command = self.okcmd )
-
- box.add( 'cancel', text='Cancel', underline=0, width=6,
- command = self.quitcmd )
-
- box.pack( side=Tix.BOTTOM, fill=Tix.X)
- top.pack( side=Tix.TOP, fill=Tix.BOTH, expand=1 )
-
- def okcmd (self):
- self.quitcmd()
-
- def quitcmd (self):
- self.exit = 0
-
- def mainloop(self):
- while self.exit < 0:
- self.root.tk.dooneevent(TCL_ALL_EVENTS)
-
- def destroy (self):
- self.root.destroy()
-
-
-# This "if" statement makes it possible to run this script file inside or
-# outside of the main demo program "tixwidgets.py".
-#
-if __name__== '__main__' :
- root=Tix.Tk()
- RunSample(root)
-
diff --git a/Demo/tix/samples/Tree.py b/Demo/tix/samples/Tree.py
deleted file mode 100755
index 2fdd7c79c5..0000000000
--- a/Demo/tix/samples/Tree.py
+++ /dev/null
@@ -1,80 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# Tix Demostration Program
-#
-# This sample program is structured in such a way so that it can be
-# executed from the Tix demo program "tixwidgets.py": it must have a
-# procedure called "RunSample". It should also have the "if" statment
-# at the end of this file so that it can be run as a standalone
-# program.
-
-# This file demonstrates how to use the TixTree widget to display
-# dynamic hierachical data (the files in the Unix file system)
-#
-
-import Tix, os
-
-def RunSample(w):
- top = Tix.Frame(w, relief=Tix.RAISED, bd=1)
- tree = Tix.Tree(top, options='separator "/"')
- tree.pack(expand=1, fill=Tix.BOTH, padx=10, pady=10, side=Tix.LEFT)
- tree['opencmd'] = lambda dir=None, w=tree: opendir(w, dir)
-
- # The / directory is added in the "open" mode. The user can open it
- # and then browse its subdirectories ...
- adddir(tree, "/")
-
- box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
- box.add('ok', text='Ok', underline=0, command=w.destroy, width=6)
- box.add('cancel', text='Cancel', underline=0, command=w.destroy, width=6)
- box.pack(side=Tix.BOTTOM, fill=Tix.X)
- top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
-
-def adddir(tree, dir):
- if dir == '/':
- text = '/'
- else:
- text = os.path.basename(dir)
- tree.hlist.add(dir, itemtype=Tix.IMAGETEXT, text=text,
- image=tree.tk.call('tix', 'getimage', 'folder'))
- try:
- os.listdir(dir)
- tree.setmode(dir, 'open')
- except os.error:
- # No read permission ?
- pass
-
-# This function is called whenever the user presses the (+) indicator or
-# double clicks on a directory whose mode is "open". It loads the files
-# inside that directory into the Tree widget.
-#
-# Note we didn't specify the closecmd option for the Tree widget, so it
-# performs the default action when the user presses the (-) indicator or
-# double clicks on a directory whose mode is "close": hide all of its child
-# entries
-def opendir(tree, dir):
- entries = tree.hlist.info_children(dir)
- if entries:
- # We have already loaded this directory. Let's just
- # show all the child entries
- #
- # Note: since we load the directory only once, it will not be
- # refreshed if the you add or remove files from this
- # directory.
- #
- for entry in entries:
- tree.hlist.show_entry(entry)
- files = os.listdir(dir)
- for file in files:
- if os.path.isdir(dir + '/' + file):
- adddir(tree, dir + '/' + file)
- else:
- tree.hlist.add(dir + '/' + file, itemtype=Tix.IMAGETEXT, text=file,
- image=tree.tk.call('tix', 'getimage', 'file'))
-
-if __name__ == '__main__':
- root = Tix.Tk()
- RunSample(root)
- root.mainloop()
diff --git a/Demo/tix/tixwidgets.py b/Demo/tix/tixwidgets.py
deleted file mode 100644
index ae7b063ee4..0000000000
--- a/Demo/tix/tixwidgets.py
+++ /dev/null
@@ -1,1004 +0,0 @@
-# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
-# $Id$
-#
-# tixwidgets.py --
-#
-# For Tix, see http://tix.sourceforge.net
-#
-# This is a demo program of some of the Tix widgets available in Python.
-# If you have installed Python & Tix properly, you can execute this as
-#
-# % python tixwidgets.py
-#
-
-import os, os.path, sys, Tix
-from Tkconstants import *
-import traceback, tkMessageBox
-
-TCL_DONT_WAIT = 1<<1
-TCL_WINDOW_EVENTS = 1<<2
-TCL_FILE_EVENTS = 1<<3
-TCL_TIMER_EVENTS = 1<<4
-TCL_IDLE_EVENTS = 1<<5
-TCL_ALL_EVENTS = 0
-
-class Demo:
- def __init__(self, top):
- self.root = top
- self.exit = -1
-
- self.dir = None # script directory
- self.balloon = None # balloon widget
- self.useBalloons = Tix.StringVar()
- self.useBalloons.set('0')
- self.statusbar = None # status bar widget
- self.welmsg = None # Msg widget
- self.welfont = '' # font name
- self.welsize = '' # font size
-
- progname = sys.argv[0]
- dirname = os.path.dirname(progname)
- if dirname and dirname != os.curdir:
- self.dir = dirname
- index = -1
- for i in range(len(sys.path)):
- p = sys.path[i]
- if p in ("", os.curdir):
- index = i
- if index >= 0:
- sys.path[index] = dirname
- else:
- sys.path.insert(0, dirname)
- else:
- self.dir = os.getcwd()
- sys.path.insert(0, self.dir+'/samples')
-
- def MkMainMenu(self):
- top = self.root
- w = Tix.Frame(top, bd=2, relief=RAISED)
- file = Tix.Menubutton(w, text='File', underline=0, takefocus=0)
- help = Tix.Menubutton(w, text='Help', underline=0, takefocus=0)
- file.pack(side=LEFT)
- help.pack(side=RIGHT)
- fm = Tix.Menu(file, tearoff=0)
- file['menu'] = fm
- hm = Tix.Menu(help, tearoff=0)
- help['menu'] = hm
-
- fm.add_command(label='Exit', underline=1,
- command = lambda self=self: self.quitcmd () )
- hm.add_checkbutton(label='BalloonHelp', underline=0, command=ToggleHelp,
- variable=self.useBalloons)
- # The trace variable option doesn't seem to work, instead I use 'command'
- #apply(w.tk.call, ('trace', 'variable', self.useBalloons, 'w',
- # ToggleHelp))
-
- return w
-
- def MkMainNotebook(self):
- top = self.root
- w = Tix.NoteBook(top, ipadx=5, ipady=5, options="""
- tagPadX 6
- tagPadY 4
- borderWidth 2
- """)
- # This may be required if there is no *Background option
- top['bg'] = w['bg']
-
- w.add('wel', label='Welcome', underline=0,
- createcmd=lambda w=w, name='wel': MkWelcome(w, name))
- w.add('cho', label='Choosers', underline=0,
- createcmd=lambda w=w, name='cho': MkChoosers(w, name))
- w.add('scr', label='Scrolled Widgets', underline=0,
- createcmd=lambda w=w, name='scr': MkScroll(w, name))
- w.add('mgr', label='Manager Widgets', underline=0,
- createcmd=lambda w=w, name='mgr': MkManager(w, name))
- w.add('dir', label='Directory List', underline=0,
- createcmd=lambda w=w, name='dir': MkDirList(w, name))
- w.add('exp', label='Run Sample Programs', underline=0,
- createcmd=lambda w=w, name='exp': MkSample(w, name))
- return w
-
- def MkMainStatus(self):
- global demo
- top = self.root
-
- w = Tix.Frame(top, relief=Tix.RAISED, bd=1)
- demo.statusbar = Tix.Label(w, relief=Tix.SUNKEN, bd=1)
- demo.statusbar.form(padx=3, pady=3, left=0, right='%70')
- return w
-
- def build(self):
- root = self.root
- z = root.winfo_toplevel()
- z.wm_title('Tix Widget Demonstration')
- if z.winfo_screenwidth() <= 800:
- z.geometry('790x590+10+10')
- else:
- z.geometry('890x640+10+10')
- demo.balloon = Tix.Balloon(root)
- frame1 = self.MkMainMenu()
- frame2 = self.MkMainNotebook()
- frame3 = self.MkMainStatus()
- frame1.pack(side=TOP, fill=X)
- frame3.pack(side=BOTTOM, fill=X)
- frame2.pack(side=TOP, expand=1, fill=BOTH, padx=4, pady=4)
- demo.balloon['statusbar'] = demo.statusbar
- z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
-
- # To show Tcl errors - uncomment this to see the listbox bug.
- # Tkinter defines a Tcl tkerror procedure that in effect
- # silences all background Tcl error reporting.
- # root.tk.eval('if {[info commands tkerror] != ""} {rename tkerror pytkerror}')
- def quitcmd (self):
- """Quit our mainloop. It is up to you to call root.destroy() after."""
- self.exit = 0
-
- def loop(self):
- """This is an explict replacement for _tkinter mainloop()
- It lets you catch keyboard interrupts easier, and avoids
- the 20 msec. dead sleep() which burns a constant CPU."""
- while self.exit < 0:
- # There are 2 whiles here. The outer one lets you continue
- # after a ^C interrupt.
- try:
- # This is the replacement for _tkinter mainloop()
- # It blocks waiting for the next Tcl event using select.
- while self.exit < 0:
- self.root.tk.dooneevent(TCL_ALL_EVENTS)
- except SystemExit:
- # Tkinter uses SystemExit to exit
- #print 'Exit'
- self.exit = 1
- return
- except KeyboardInterrupt:
- if tkMessageBox.askquestion ('Interrupt', 'Really Quit?') == 'yes':
- # self.tk.eval('exit')
- self.exit = 1
- return
- continue
- except:
- # Otherwise it's some other error - be nice and say why
- t, v, tb = sys.exc_info()
- text = ""
- for line in traceback.format_exception(t,v,tb):
- text += line + '\n'
- try: tkMessageBox.showerror ('Error', text)
- except: pass
- self.exit = 1
- raise SystemExit, 1
-
- def destroy (self):
- self.root.destroy()
-
-def RunMain(root):
- global demo
-
- demo = Demo(root)
-
- demo.build()
- demo.loop()
- demo.destroy()
-
-# Tabs
-def MkWelcome(nb, name):
- w = nb.page(name)
- bar = MkWelcomeBar(w)
- text = MkWelcomeText(w)
- bar.pack(side=TOP, fill=X, padx=2, pady=2)
- text.pack(side=TOP, fill=BOTH, expand=1)
-
-def MkWelcomeBar(top):
- global demo
-
- w = Tix.Frame(top, bd=2, relief=Tix.GROOVE)
- b1 = Tix.ComboBox(w, command=lambda w=top: MainTextFont(w))
- b2 = Tix.ComboBox(w, command=lambda w=top: MainTextFont(w))
- b1.entry['width'] = 15
- b1.slistbox.listbox['height'] = 3
- b2.entry['width'] = 4
- b2.slistbox.listbox['height'] = 3
-
- demo.welfont = b1
- demo.welsize = b2
-
- b1.insert(Tix.END, 'Courier')
- b1.insert(Tix.END, 'Helvetica')
- b1.insert(Tix.END, 'Lucida')
- b1.insert(Tix.END, 'Times Roman')
-
- b2.insert(Tix.END, '8')
- b2.insert(Tix.END, '10')
- b2.insert(Tix.END, '12')
- b2.insert(Tix.END, '14')
- b2.insert(Tix.END, '18')
-
- b1.pick(1)
- b2.pick(3)
-
- b1.pack(side=Tix.LEFT, padx=4, pady=4)
- b2.pack(side=Tix.LEFT, padx=4, pady=4)
-
- demo.balloon.bind_widget(b1, msg='Choose\na font',
- statusmsg='Choose a font for this page')
- demo.balloon.bind_widget(b2, msg='Point size',
- statusmsg='Choose the font size for this page')
- return w
-
-def MkWelcomeText(top):
- global demo
-
- w = Tix.ScrolledWindow(top, scrollbar='auto')
- win = w.window
- text = 'Welcome to TIX in Python'
- title = Tix.Label(win,
- bd=0, width=30, anchor=Tix.N, text=text)
- msg = Tix.Message(win,
- bd=0, width=400, anchor=Tix.N,
- text='Tix is a set of mega-widgets based on TK. This program \
-demonstrates the widgets in the Tix widget set. You can choose the pages \
-in this window to look at the corresponding widgets. \n\n\
-To quit this program, choose the "File | Exit" command.\n\n\
-For more information, see http://tix.sourceforge.net.')
- title.pack(expand=1, fill=Tix.BOTH, padx=10, pady=10)
- msg.pack(expand=1, fill=Tix.BOTH, padx=10, pady=10)
- demo.welmsg = msg
- return w
-
-def MainTextFont(w):
- global demo
-
- if not demo.welmsg:
- return
- font = demo.welfont['value']
- point = demo.welsize['value']
- if font == 'Times Roman':
- font = 'times'
- fontstr = '%s %s' % (font, point)
- demo.welmsg['font'] = fontstr
-
-def ToggleHelp():
- if demo.useBalloons.get() == '1':
- demo.balloon['state'] = 'both'
- else:
- demo.balloon['state'] = 'none'
-
-def MkChoosers(nb, name):
- w = nb.page(name)
- options = "label.padX 4"
-
- til = Tix.LabelFrame(w, label='Chooser Widgets', options=options)
- cbx = Tix.LabelFrame(w, label='tixComboBox', options=options)
- ctl = Tix.LabelFrame(w, label='tixControl', options=options)
- sel = Tix.LabelFrame(w, label='tixSelect', options=options)
- opt = Tix.LabelFrame(w, label='tixOptionMenu', options=options)
- fil = Tix.LabelFrame(w, label='tixFileEntry', options=options)
- fbx = Tix.LabelFrame(w, label='tixFileSelectBox', options=options)
- tbr = Tix.LabelFrame(w, label='Tool Bar', options=options)
-
- MkTitle(til.frame)
- MkCombo(cbx.frame)
- MkControl(ctl.frame)
- MkSelect(sel.frame)
- MkOptMenu(opt.frame)
- MkFileEnt(fil.frame)
- MkFileBox(fbx.frame)
- MkToolBar(tbr.frame)
-
- # First column: comBox and selector
- cbx.form(top=0, left=0, right='%33')
- sel.form(left=0, right='&'+str(cbx), top=cbx)
- opt.form(left=0, right='&'+str(cbx), top=sel, bottom=-1)
-
- # Second column: title .. etc
- til.form(left=cbx, top=0,right='%66')
- ctl.form(left=cbx, right='&'+str(til), top=til)
- fil.form(left=cbx, right='&'+str(til), top=ctl)
- tbr.form(left=cbx, right='&'+str(til), top=fil, bottom=-1)
-
- #
- # Third column: file selection
- fbx.form(right=-1, top=0, left='%66')
-
-def MkCombo(w):
- options="label.width %d label.anchor %s entry.width %d" % (10, Tix.E, 14)
-
- static = Tix.ComboBox(w, label='Static', editable=0, options=options)
- editable = Tix.ComboBox(w, label='Editable', editable=1, options=options)
- history = Tix.ComboBox(w, label='History', editable=1, history=1,
- anchor=Tix.E, options=options)
- static.insert(Tix.END, 'January')
- static.insert(Tix.END, 'February')
- static.insert(Tix.END, 'March')
- static.insert(Tix.END, 'April')
- static.insert(Tix.END, 'May')
- static.insert(Tix.END, 'June')
- static.insert(Tix.END, 'July')
- static.insert(Tix.END, 'August')
- static.insert(Tix.END, 'September')
- static.insert(Tix.END, 'October')
- static.insert(Tix.END, 'November')
- static.insert(Tix.END, 'December')
-
- editable.insert(Tix.END, 'Angola')
- editable.insert(Tix.END, 'Bangladesh')
- editable.insert(Tix.END, 'China')
- editable.insert(Tix.END, 'Denmark')
- editable.insert(Tix.END, 'Ecuador')
-
- history.insert(Tix.END, '/usr/bin/ksh')
- history.insert(Tix.END, '/usr/local/lib/python')
- history.insert(Tix.END, '/var/adm')
-
- static.pack(side=Tix.TOP, padx=5, pady=3)
- editable.pack(side=Tix.TOP, padx=5, pady=3)
- history.pack(side=Tix.TOP, padx=5, pady=3)
-
-states = ['Bengal', 'Delhi', 'Karnataka', 'Tamil Nadu']
-
-def spin_cmd(w, inc):
- idx = states.index(demo_spintxt.get()) + inc
- if idx < 0:
- idx = len(states) - 1
- elif idx >= len(states):
- idx = 0
-# following doesn't work.
-# return states[idx]
- demo_spintxt.set(states[idx]) # this works
-
-def spin_validate(w):
- global states, demo_spintxt
-
- try:
- i = states.index(demo_spintxt.get())
- except ValueError:
- return states[0]
- return states[i]
- # why this procedure works as opposed to the previous one beats me.
-
-def MkControl(w):
- global demo_spintxt
-
- options="label.width %d label.anchor %s entry.width %d" % (10, Tix.E, 13)
-
- demo_spintxt = Tix.StringVar()
- demo_spintxt.set(states[0])
- simple = Tix.Control(w, label='Numbers', options=options)
- spintxt = Tix.Control(w, label='States', variable=demo_spintxt,
- options=options)
- spintxt['incrcmd'] = lambda w=spintxt: spin_cmd(w, 1)
- spintxt['decrcmd'] = lambda w=spintxt: spin_cmd(w, -1)
- spintxt['validatecmd'] = lambda w=spintxt: spin_validate(w)
-
- simple.pack(side=Tix.TOP, padx=5, pady=3)
- spintxt.pack(side=Tix.TOP, padx=5, pady=3)
-
-def MkSelect(w):
- options = "label.anchor %s" % Tix.CENTER
-
- sel1 = Tix.Select(w, label='Mere Mortals', allowzero=1, radio=1,
- orientation=Tix.VERTICAL,
- labelside=Tix.TOP,
- options=options)
- sel2 = Tix.Select(w, label='Geeks', allowzero=1, radio=0,
- orientation=Tix.VERTICAL,
- labelside= Tix.TOP,
- options=options)
-
- sel1.add('eat', text='Eat')
- sel1.add('work', text='Work')
- sel1.add('play', text='Play')
- sel1.add('party', text='Party')
- sel1.add('sleep', text='Sleep')
-
- sel2.add('eat', text='Eat')
- sel2.add('prog1', text='Program')
- sel2.add('prog2', text='Program')
- sel2.add('prog3', text='Program')
- sel2.add('sleep', text='Sleep')
-
- sel1.pack(side=Tix.LEFT, padx=5, pady=3, fill=Tix.X)
- sel2.pack(side=Tix.LEFT, padx=5, pady=3, fill=Tix.X)
-
-def MkOptMenu(w):
- options='menubutton.width 15 label.anchor %s' % Tix.E
-
- m = Tix.OptionMenu(w, label='File Format : ', options=options)
- m.add_command('text', label='Plain Text')
- m.add_command('post', label='PostScript')
- m.add_command('format', label='Formatted Text')
- m.add_command('html', label='HTML')
- m.add_command('sep')
- m.add_command('tex', label='LaTeX')
- m.add_command('rtf', label='Rich Text Format')
-
- m.pack(fill=Tix.X, padx=5, pady=3)
-
-def MkFileEnt(w):
- msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='Press the "open file" icon button and a TixFileSelectDialog will popup.')
- ent = Tix.FileEntry(w, label='Select a file : ')
- msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
- ent.pack(side=Tix.TOP, fill=Tix.X, padx=3, pady=3)
-
-def MkFileBox(w):
- """The FileSelectBox is a Motif-style box with various enhancements.
- For example, you can adjust the size of the two listboxes
- and your past selections are recorded.
- """
- msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The Tix FileSelectBox is a Motif-style box with various enhancements. For example, you can adjust the size of the two listboxes and your past selections are recorded.')
- box = Tix.FileSelectBox(w)
- msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
- box.pack(side=Tix.TOP, fill=Tix.X, padx=3, pady=3)
-
-def MkToolBar(w):
- """The Select widget is also good for arranging buttons in a tool bar.
- """
- global demo
-
- options='frame.borderWidth 1'
-
- msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The Select widget is also good for arranging buttons in a tool bar.')
- bar = Tix.Frame(w, bd=2, relief=Tix.RAISED)
- font = Tix.Select(w, allowzero=1, radio=0, label='', options=options)
- para = Tix.Select(w, allowzero=0, radio=1, label='', options=options)
-
- font.add('bold', bitmap='@' + demo.dir + '/bitmaps/bold.xbm')
- font.add('italic', bitmap='@' + demo.dir + '/bitmaps/italic.xbm')
- font.add('underline', bitmap='@' + demo.dir + '/bitmaps/underline.xbm')
- font.add('capital', bitmap='@' + demo.dir + '/bitmaps/capital.xbm')
-
- para.add('left', bitmap='@' + demo.dir + '/bitmaps/leftj.xbm')
- para.add('right', bitmap='@' + demo.dir + '/bitmaps/rightj.xbm')
- para.add('center', bitmap='@' + demo.dir + '/bitmaps/centerj.xbm')
- para.add('justify', bitmap='@' + demo.dir + '/bitmaps/justify.xbm')
-
- msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
- bar.pack(side=Tix.TOP, fill=Tix.X, padx=3, pady=3)
- font.pack({'in':bar}, side=Tix.LEFT, padx=3, pady=3)
- para.pack({'in':bar}, side=Tix.LEFT, padx=3, pady=3)
-
-def MkTitle(w):
- msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='There are many types of "chooser" widgets that allow the user to input different types of information')
- msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
-
-def MkScroll(nb, name):
- w = nb.page(name)
- options='label.padX 4'
-
- sls = Tix.LabelFrame(w, label='Tix.ScrolledListBox', options=options)
- swn = Tix.LabelFrame(w, label='Tix.ScrolledWindow', options=options)
- stx = Tix.LabelFrame(w, label='Tix.ScrolledText', options=options)
-
- MkSList(sls.frame)
- MkSWindow(swn.frame)
- MkSText(stx.frame)
-
- sls.form(top=0, left=0, right='%33', bottom=-1)
- swn.form(top=0, left=sls, right='%66', bottom=-1)
- stx.form(top=0, left=swn, right=-1, bottom=-1)
-
-
-def MkSList(w):
- """This TixScrolledListBox is configured so that it uses scrollbars
- only when it is necessary. Use the handles to resize the listbox and
- watch the scrollbars automatically appear and disappear. """
- top = Tix.Frame(w, width=300, height=330)
- bot = Tix.Frame(w)
- msg = Tix.Message(top,
- relief=Tix.FLAT, width=200, anchor=Tix.N,
- text='This TixScrolledListBox is configured so that it uses scrollbars only when it is necessary. Use the handles to resize the listbox and watch the scrollbars automatically appear and disappear.')
-
- list = Tix.ScrolledListBox(top, scrollbar='auto')
- list.place(x=50, y=150, width=120, height=80)
- list.listbox.insert(Tix.END, 'Alabama')
- list.listbox.insert(Tix.END, 'California')
- list.listbox.insert(Tix.END, 'Montana')
- list.listbox.insert(Tix.END, 'New Jersey')
- list.listbox.insert(Tix.END, 'New York')
- list.listbox.insert(Tix.END, 'Pennsylvania')
- list.listbox.insert(Tix.END, 'Washington')
-
- rh = Tix.ResizeHandle(top, bg='black',
- relief=Tix.RAISED,
- handlesize=8, gridded=1, minwidth=50, minheight=30)
- btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=list: SList_reset(w,x))
- top.propagate(0)
- msg.pack(fill=Tix.X)
- btn.pack(anchor=Tix.CENTER)
- top.pack(expand=1, fill=Tix.BOTH)
- bot.pack(fill=Tix.BOTH)
- list.bind('
-
-
-
-Converted to HTML by sax_rss2html.py.
-
-
-
-
-"""
-
-# --- The ContentHandler
-
-class RSSHandler(handler.ContentHandler):
-
- def __init__(self, out = sys.stdout):
- handler.ContentHandler.__init__(self)
- self._out = out
-
- self._text = ""
- self._parent = None
- self._list_started = 0
- self._title = None
- self._link = None
- self._descr = ""
-
- # ContentHandler methods
-
- def startElement(self, name, attrs):
- if name == "channel" or name == "image" or name == "item":
- self._parent = name
-
- self._text = ""
-
- def endElement(self, name):
- if self._parent == "channel":
- if name == "title":
- self._out.write(top % (self._text, self._text))
- elif name == "description":
- self._out.write("
%s
\n" % self._text)
-
- elif self._parent == "item":
- if name == "title":
- self._title = self._text
- elif name == "link":
- self._link = self._text
- elif name == "description":
- self._descr = self._text
- elif name == "item":
- if not self._list_started:
- self._out.write("
%s %s\n' %
- (self._link, self._title, self._descr))
-
- self._title = None
- self._link = None
- self._descr = ""
-
- if name == "rss":
- self._out.write(bottom)
-
- def characters(self, content):
- self._text = self._text + content
-
-# --- Main program
-
-parser = make_parser()
-parser.setContentHandler(RSSHandler())
-parser.parse(sys.argv[1])
diff --git a/Demo/xmlrpc/xmlrpc_handler.py b/Demo/xmlrpc/xmlrpc_handler.py
deleted file mode 100644
index 1935475166..0000000000
--- a/Demo/xmlrpc/xmlrpc_handler.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#
-# XML-RPC SERVER
-# $Id$
-#
-# an asynchronous XML-RPC server for Medusa
-#
-# written by Sam Rushing
-#
-# Based on "xmlrpcserver.py" by Fredrik Lundh (fredrik@pythonware.com)
-#
-
-import http_server
-import xmlrpclib
-
-import sys
-
-class xmlrpc_handler:
-
- def match (self, request):
- # Note: /RPC2 is not required by the spec, so you may override this method.
- if request.uri[:5] == '/RPC2':
- return 1
- else:
- return 0
-
- def handle_request (self, request):
- [path, params, query, fragment] = request.split_uri()
-
- if request.command in ('post', 'put'):
- request.collector = collector (self, request)
- else:
- request.error (400)
-
- def continue_request (self, data, request):
- params, method = xmlrpclib.loads (data)
- try:
- # generate response
- try:
- response = self.call (method, params)
- response = (response,)
- except:
- # report exception back to server
- response = xmlrpclib.dumps (
- xmlrpclib.Fault (1, "%s:%s" % sys.exc_info()[:2])
- )
- else:
- response = xmlrpclib.dumps (response, methodresponse=1)
- except:
- # internal error, report as HTTP server error
- request.error (500)
- else:
- # got a valid XML RPC response
- request['Content-Type'] = 'text/xml'
- request.push (response)
- request.done()
-
- def call (self, method, params):
- # override this method to implement RPC methods
- raise "NotYetImplemented"
-
-class collector:
-
- "gathers input for POST and PUT requests"
-
- def __init__ (self, handler, request):
-
- self.handler = handler
- self.request = request
- self.data = ''
-
- # make sure there's a content-length header
- cl = request.get_header ('content-length')
-
- if not cl:
- request.error (411)
- else:
- cl = int (cl)
- # using a 'numeric' terminator
- self.request.channel.set_terminator (cl)
-
- def collect_incoming_data (self, data):
- self.data = self.data + data
-
- def found_terminator (self):
- # set the terminator back to the default
- self.request.channel.set_terminator ('\r\n\r\n')
- self.handler.continue_request (self.data, self.request)
-
-if __name__ == '__main__':
-
- class rpc_demo (xmlrpc_handler):
-
- def call (self, method, params):
- print 'method="%s" params=%s' % (method, params)
- return "Sure, that works"
-
- import asyncore
- import http_server
-
- hs = http_server.http_server ('', 8000)
- rpc = rpc_demo()
- hs.install_handler (rpc)
-
- asyncore.loop()
diff --git a/Demo/xmlrpc/xmlrpcserver.py b/Demo/xmlrpc/xmlrpcserver.py
deleted file mode 100644
index 7af73bec99..0000000000
--- a/Demo/xmlrpc/xmlrpcserver.py
+++ /dev/null
@@ -1,75 +0,0 @@
-#
-# XML-RPC SERVER
-# $Id$
-#
-# a simple XML-RPC server for Python
-#
-# History:
-# 1999-02-01 fl added to xmlrpclib distribution
-#
-# written by Fredrik Lundh, January 1999.
-#
-# Copyright (c) 1999 by Secret Labs AB.
-# Copyright (c) 1999 by Fredrik Lundh.
-#
-# fredrik@pythonware.com
-# http://www.pythonware.com
-#
-# --------------------------------------------------------------------
-# Permission to use, copy, modify, and distribute this software and
-# its associated documentation for any purpose and without fee is
-# hereby granted. This software is provided as is.
-# --------------------------------------------------------------------
-#
-
-import SocketServer, BaseHTTPServer
-import xmlrpclib
-import sys
-
-class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
-
- def do_POST(self):
- try:
- # get arguments
- data = self.rfile.read(int(self.headers["content-length"]))
- params, method = xmlrpclib.loads(data)
-
- # generate response
- try:
- response = self.call(method, params)
- # wrap response in a singleton tuple
- response = (response,)
- except:
- # report exception back to server
- response = xmlrpclib.dumps(
- xmlrpclib.Fault(1, "%s:%s" % sys.exc_info()[:2])
- )
- else:
- response = xmlrpclib.dumps(
- response,
- methodresponse=1
- )
- except:
- # internal error, report as HTTP server error
- self.send_response(500)
- self.end_headers()
- else:
- # got a valid XML RPC response
- self.send_response(200)
- self.send_header("Content-type", "text/xml")
- self.send_header("Content-length", str(len(response)))
- self.end_headers()
- self.wfile.write(response)
-
- # shut down the connection (from Skip Montanaro)
- self.wfile.flush()
- self.connection.shutdown(1)
-
- def call(self, method, params):
- # override this method to implement RPC methods
- print "CALL", method, params
- return params
-
-if __name__ == '__main__':
- server = SocketServer.TCPServer(('', 8000), RequestHandler)
- server.serve_forever()
diff --git a/Demo/zlib/minigzip.py b/Demo/zlib/minigzip.py
deleted file mode 100755
index dc99d9bc88..0000000000
--- a/Demo/zlib/minigzip.py
+++ /dev/null
@@ -1,107 +0,0 @@
-#!/usr/bin/env python
-# Demo program for zlib; it compresses or decompresses files, but *doesn't*
-# delete the original. This doesn't support all of gzip's options.
-
-FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
-
-def write32(output, value):
- output.write(chr(value & 255)) ; value=value / 256
- output.write(chr(value & 255)) ; value=value / 256
- output.write(chr(value & 255)) ; value=value / 256
- output.write(chr(value & 255))
-
-def read32(input):
- v=ord(input.read(1))
- v=v+ (ord(input.read(1))<<8 )
- v=v+ (ord(input.read(1))<<16)
- v=v+ (ord(input.read(1))<<24)
- return v
-
-import zlib, sys
-if len(sys.argv)!=2:
- print 'Usage: minigzip.py '
- print ' The file will be compressed or decompressed.'
- sys.exit(0)
-
-filename=sys.argv[1]
-compressing=1 ; outputname=filename+'.gz'
-if filename[-3:]=='.gz':
- compressing=0 ; outputname=filename[:-3]
-input=open(filename) ; output=open(outputname, 'w')
-
-if compressing:
- output.write('\037\213\010') # Write the header, ...
- output.write(chr(FNAME)) # ... flag byte ...
-
- import os # ... modification time ...
- statval=os.stat(filename)
- mtime=statval[8]
- write32(output, mtime)
- output.write('\002') # ... slowest compression alg. ...
- output.write('\377') # ... OS (=unknown) ...
- output.write(filename+'\000') # ... original filename ...
-
- crcval=zlib.crc32("")
- compobj=zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS,
- zlib.DEF_MEM_LEVEL, 0)
- while (1):
- data=input.read(1024)
- if data=="": break
- crcval=zlib.crc32(data, crcval)
- output.write(compobj.compress(data))
- output.write(compobj.flush())
- write32(output, crcval) # ... the CRC ...
- write32(output, statval[6]) # and the file size.
-
-else:
- magic=input.read(2)
- if magic!='\037\213':
- print 'Not a gzipped file' ; sys.exit(0)
- if ord(input.read(1))!=8:
- print 'Unknown compression method' ; sys.exit(0)
- flag=ord(input.read(1))
- input.read(4+1+1) # Discard modification time,
- # extra flags, and OS byte.
- if flag & FEXTRA:
- # Read & discard the extra field, if present
- xlen=ord(input.read(1))
- xlen=xlen+256*ord(input.read(1))
- input.read(xlen)
- if flag & FNAME:
- # Read and discard a null-terminated string containing the filename
- while (1):
- s=input.read(1)
- if s=='\000': break
- if flag & FCOMMENT:
- # Read and discard a null-terminated string containing a comment
- while (1):
- s=input.read(1)
- if s=='\000': break
- if flag & FHCRC:
- input.read(2) # Read & discard the 16-bit header CRC
- decompobj=zlib.decompressobj(-zlib.MAX_WBITS)
- crcval=zlib.crc32("")
- length=0
- while (1):
- data=input.read(1024)
- if data=="": break
- decompdata=decompobj.decompress(data)
- print len(decompdata)
- output.write(decompdata) ; length=length+len(decompdata)
- crcval=zlib.crc32(decompdata, crcval)
- decompdata=decompobj.flush()
- output.write(decompdata) ; length=length+len(decompdata)
- crcval=zlib.crc32(decompdata, crcval)
-
- # We've read to the end of the file, so we have to rewind in order
- # to reread the 8 bytes containing the CRC and the file size. The
- # decompressor is smart and knows when to stop, so feeding it
- # extra data is harmless.
- input.seek(-8, 2)
- crc32=read32(input)
- isize=read32(input)
- if crc32!=crcval: print 'CRC check failed.'
- if isize!=length: print 'Incorrect length of data produced'
-
-input.close() ; output.close()
-
diff --git a/Demo/zlib/zlibdemo.py b/Demo/zlib/zlibdemo.py
deleted file mode 100755
index 7c56e3e662..0000000000
--- a/Demo/zlib/zlibdemo.py
+++ /dev/null
@@ -1,36 +0,0 @@
-#!/usr/bin/env python
-
-import zlib, sys
-if len(sys.argv)>1: filename=sys.argv[1]
-else: filename='zlibdemo.py'
-print 'Reading', filename
-f=open(filename, 'r') # Get the data to compress
-s=f.read()
-f.close()
-
-# First, we'll compress the string in one step
-comptext=zlib.compress(s, 1)
-decomp=zlib.decompress(comptext)
-
-print '1-step compression: (level 1)'
-print ' Original:', len(s), 'Compressed:', len(comptext),
-print 'Uncompressed:', len(decomp)
-
-# Now, let's compress the string in stages; set chunk to work in smaller steps
-
-chunk=256
-compressor=zlib.compressobj(9)
-decompressor=zlib.decompressobj()
-comptext=decomp=''
-for i in range(0, len(s), chunk):
- comptext=comptext+compressor.compress(s[i:i+chunk])
-comptext=comptext+compressor.flush() # Don't forget to call flush()!!
-
-for i in range(0, len(comptext), chunk):
- decomp=decomp+decompressor.decompress(comptext[i:i+chunk])
-decomp=decomp+decompressor.flush()
-
-print 'Progressive compression (level 9):'
-print ' Original:', len(s), 'Compressed:', len(comptext),
-print 'Uncompressed:', len(decomp)
-
diff --git a/Doc/.cvsignore b/Doc/.cvsignore
deleted file mode 100755
index b5159d8f3f..0000000000
--- a/Doc/.cvsignore
+++ /dev/null
@@ -1,5 +0,0 @@
-*.tgz
-*.tar.bz2
-*.zip
-*.tar
-pkglist.html
diff --git a/Doc/ACKS b/Doc/ACKS
deleted file mode 100644
index e5d6297316..0000000000
--- a/Doc/ACKS
+++ /dev/null
@@ -1,196 +0,0 @@
-Contributors to the Python Documentation
-----------------------------------------
-
-This file lists people who have contributed in some way to the Python
-documentation. It is probably not complete -- if you feel that you or
-anyone else should be on this list, please let us know (send email to
-python-docs@python.org), and we'll be glad to correct the problem.
-
-It is only with the input and contributions of the Python community
-that Python has such wonderful documentation -- Thank You!
-
-In the official sources, this file is encoded in ISO-8859-1 (Latin-1).
-
-
- -Fred
-
-
-Aahz
-Michael Abbott
-Steve Alexander
-Jim Ahlstrom
-Fred Allen
-A. Amoroso
-Pehr Anderson
-Oliver Andrich
-Jesús Cea Avión
-Daniel Barclay
-Chris Barker
-Don Bashford
-Anthony Baxter
-Bennett Benson
-Jonathan Black
-Robin Boerdijk
-Michal Bozon
-Aaron Brancotti
-Keith Briggs
-Lee Busby
-Lorenzo M. Catucci
-Mauro Cicognini
-Gilles Civario
-Mike Clarkson
-Steve Clift
-Dave Cole
-Matthew Cowles
-Jeremy Craven
-Andrew Dalke
-Ben Darnell
-L. Peter Deutsch
-Robert Donohue
-Fred L. Drake, Jr.
-Jeff Epler
-Michael Ernst
-Blame Andy Eskilsson
-Carey Evans
-Martijn Faassen
-Carl Feynman
-Hernán Martínez Foffani
-Stefan Franke
-Jim Fulton
-Peter Funk
-Lele Gaifax
-Matthew Gallagher
-Ben Gertzfield
-Nadim Ghaznavi
-Jonathan Giddy
-Shelley Gooch
-Nathaniel Gray
-Grant Griffin
-Thomas Guettler
-Anders Hammarquist
-Mark Hammond
-Harald Hanche-Olsen
-Manus Hand
-Gerhard Häring
-Travis B. Hartwell
-Janko Hauser
-Bernhard Herzog
-Magnus L. Hetland
-Konrad Hinsen
-Stefan Hoffmeister
-Albert Hofkamp
-Gregor Hoffleit
-Steve Holden
-Thomas Holenstein
-Gerrit Holl
-Rob Hooft
-Brian Hooper
-Randall Hopper
-Michael Hudson
-Eric Huss
-Jeremy Hylton
-Roger Irwin
-Jack Jansen
-Philip H. Jensen
-Pedro Diaz Jimenez
-Lucas de Jonge
-Andreas Jung
-Robert Kern
-Jim Kerr
-Jan Kim
-Greg Kochanski
-Guido Kollerie
-Peter A. Koren
-Daniel Kozan
-Andrew M. Kuchling
-Dave Kuhlman
-Erno Kuusela
-Detlef Lannert
-Piers Lauder
-Glyph Lefkowitz
-Marc-André Lemburg
-Ulf A. Lindgren
-Everett Lipman
-Mirko Liss
-Martin von Löwis
-Fredrik Lundh
-Jeff MacDonald
-John Machin
-Andrew MacIntyre
-Vladimir Marangozov
-Vincent Marchetti
-Laura Matson
-Daniel May
-Doug Mennella
-Paolo Milani
-Skip Montanaro
-Paul Moore
-Ross Moore
-Sjoerd Mullender
-Dale Nagata
-Ng Pheng Siong
-Koray Oner
-Tomas Oppelstrup
-Denis S. Otkidach
-Zooko O'Whielacronx
-William Park
-Joonas Paalasmaa
-Harri Pasanen
-Tim Peters
-Christopher Petrilli
-Justin D. Pettit
-Chris Phoenix
-François Pinard
-Paul Prescod
-Eric S. Raymond
-Edward K. Ream
-Sean Reifschneider
-Bernhard Reiter
-Armin Rigo
-Wes Rishel
-Jim Roskind
-Guido van Rossum
-Donald Wallace Rouse II
-Nick Russo
-Chris Ryland
-Constantina S.
-Hugh Sasse
-Bob Savage
-Scott Schram
-Neil Schemenauer
-Barry Scott
-Joakim Sernbrant
-Justin Sheehy
-Michael Simcich
-Ionel Simionescu
-Roy Smith
-Clay Spence
-Nicholas Spies
-Tage Stabell-Kulo
-Frank Stajano
-Anthony Starks
-Greg Stein
-Peter Stoehr
-Mark Summerfield
-Reuben Sumner
-Kalle Svensson
-Jim Tittsler
-Martijn Vries
-Charles G. Waldman
-Greg Ward
-Barry Warsaw
-Corran Webster
-Glyn Webster
-Bob Weiner
-Eddy Welbourne
-Mats Wichmann
-Gerry Wiener
-Timothy Wild
-Blake Winton
-Dan Wolfe
-Steven Work
-Thomas Wouters
-Ka-Ping Yee
-Moshe Zadka
-Milan Zamazal
-Cheng Zhang
diff --git a/Doc/Makefile b/Doc/Makefile
deleted file mode 100644
index 012ba48e00..0000000000
--- a/Doc/Makefile
+++ /dev/null
@@ -1,691 +0,0 @@
-# Makefile for Python documentation
-# ---------------------------------
-#
-# See also the README file.
-#
-# This is a bit of a mess. The documents are identified by short names:
-# api -- Python/C API Reference Manual
-# doc -- Documenting Python
-# ext -- Extending and Embedding the Python Interpreter
-# lib -- Library Reference Manual
-# mac -- Macintosh Library Modules
-# ref -- Python Reference Manual
-# tut -- Python Tutorial
-# inst -- Installing Python Modules
-# dist -- Distributing Python Modules
-#
-# The LaTeX sources for each of these documents are in subdirectories
-# with the three-letter designations above as the directory names.
-#
-# The main target creates HTML for each of the documents. You can
-# also do "make lib" (etc.) to create the HTML versions of individual
-# documents.
-#
-# The document classes and styles are in the texinputs/ directory.
-# These define a number of macros that are similar in name and intent
-# as macros in Texinfo (e.g. \code{...} and \emph{...}), as well as a
-# number of environments for formatting function and data definitions.
-# Documentation for the macros is included in "Documenting Python"; see
-# http://www.python.org/doc/current/doc/doc.html, or the sources for
-# this document in the doc/ directory.
-#
-# Everything is processed by LaTeX. See the file `README' for more
-# information on the tools needed for processing.
-#
-# There's a problem with generating the index which has been solved by
-# a sed command applied to the index file. The shell script fix_hack
-# does this (the Makefile takes care of calling it).
-#
-# Additional targets attempt to convert selected LaTeX sources to
-# various other formats. These are generally site specific because
-# the tools used are all but universal. These targets are:
-#
-# ps -- convert all documents from LaTeX to PostScript
-# pdf -- convert all documents from LaTeX to the
-# Portable Document Format
-#
-# See the README file for more information on these targets.
-#
-# The formatted output is located in subdirectories. For PDF and
-# PostScript, look in the paper-$(PAPER)/ directory. For HTML, look in
-# the html/ directory. If you want to fix the GNU info process, look
-# in the info/ directory; please send patches to python-docs@python.org.
-
-# This Makefile only includes information on how to perform builds; for
-# dependency information, see Makefile.deps.
-
-# Customization -- you *may* have to edit this
-
-# You could set this to a4:
-PAPER=letter
-
-# Ideally, you shouldn't need to edit beyond this point
-
-INFODIR= info
-TOOLSDIR= tools
-
-# This is the *documentation* release, and is used to construct the file
-# names of the downloadable tarballs.
-RELEASE=2.3b1
-
-PYTHON= python
-DVIPS= dvips -N0 -t $(PAPER)
-
-MKDVI= $(PYTHON) ../tools/mkhowto --paper=$(PAPER) --dvi
-MKHTML= $(PYTHON) tools/mkhowto --html --about html/stdabout.dat \
- --iconserver ../icons --favicon ../icons/pyfav.gif \
- --address $(PYTHONDOCS) --up-link ../index.html \
- --up-title "Python Documentation Index" \
- --global-module-index "../modindex.html" --dvips-safe
-MKISILOHTML=$(PYTHON) tools/mkhowto --html --about html/stdabout.dat \
- --iconserver ../icons \
- --l2h-init perl/isilo.perl --numeric --split 1 \
- --dvips-safe
-MKISILO= iSilo386 -U -y -rCR -d0
-MKPDF= $(PYTHON) ../tools/mkhowto --paper=$(PAPER) --pdf
-MKPS= $(PYTHON) ../tools/mkhowto --paper=$(PAPER) --ps
-
-BUILDINDEX=$(TOOLSDIR)/buildindex.py
-
-PYTHONDOCS="See About this document... for information on suggesting changes."
-HTMLBASE= file:`pwd`
-
-# The emacs binary used to build the info docs. GNU Emacs 21 is required.
-EMACS= emacs
-
-# The end of this should reflect the major/minor version numbers of
-# the release:
-WHATSNEW=whatsnew23
-
-# what's what
-MANDVIFILES= paper-$(PAPER)/api.dvi paper-$(PAPER)/ext.dvi \
- paper-$(PAPER)/lib.dvi paper-$(PAPER)/mac.dvi \
- paper-$(PAPER)/ref.dvi paper-$(PAPER)/tut.dvi
-HOWTODVIFILES= paper-$(PAPER)/doc.dvi paper-$(PAPER)/inst.dvi \
- paper-$(PAPER)/dist.dvi paper-$(PAPER)/$(WHATSNEW).dvi
-
-MANPDFFILES= paper-$(PAPER)/api.pdf paper-$(PAPER)/ext.pdf \
- paper-$(PAPER)/lib.pdf paper-$(PAPER)/mac.pdf \
- paper-$(PAPER)/ref.pdf paper-$(PAPER)/tut.pdf
-HOWTOPDFFILES= paper-$(PAPER)/doc.pdf paper-$(PAPER)/inst.pdf \
- paper-$(PAPER)/dist.pdf paper-$(PAPER)/$(WHATSNEW).pdf
-
-MANPSFILES= paper-$(PAPER)/api.ps paper-$(PAPER)/ext.ps \
- paper-$(PAPER)/lib.ps paper-$(PAPER)/mac.ps \
- paper-$(PAPER)/ref.ps paper-$(PAPER)/tut.ps
-HOWTOPSFILES= paper-$(PAPER)/doc.ps paper-$(PAPER)/inst.ps \
- paper-$(PAPER)/dist.ps paper-$(PAPER)/$(WHATSNEW).ps
-
-DVIFILES= $(MANDVIFILES) $(HOWTODVIFILES)
-PDFFILES= $(MANPDFFILES) $(HOWTOPDFFILES)
-PSFILES= $(MANPSFILES) $(HOWTOPSFILES)
-
-HTMLCSSFILES=html/api/api.css \
- html/doc/doc.css \
- html/ext/ext.css \
- html/lib/lib.css \
- html/mac/mac.css \
- html/ref/ref.css \
- html/tut/tut.css \
- html/inst/inst.css \
- html/dist/dist.css
-
-ISILOCSSFILES=isilo/api/api.css \
- isilo/doc/doc.css \
- isilo/ext/ext.css \
- isilo/lib/lib.css \
- isilo/mac/mac.css \
- isilo/ref/ref.css \
- isilo/tut/tut.css \
- isilo/inst/inst.css \
- isilo/dist/dist.css
-
-ALLCSSFILES=$(HTMLCSSFILES) $(ISILOCSSFILES)
-
-INDEXFILES=html/api/api.html \
- html/doc/doc.html \
- html/ext/ext.html \
- html/lib/lib.html \
- html/mac/mac.html \
- html/ref/ref.html \
- html/tut/tut.html \
- html/inst/inst.html \
- html/dist/dist.html \
- html/whatsnew/$(WHATSNEW).html
-
-ALLHTMLFILES=$(INDEXFILES) html/index.html html/modindex.html html/acks.html
-
-COMMONPERL= perl/manual.perl perl/python.perl perl/l2hinit.perl
-
-ANNOAPI=api/refcounts.dat tools/anno-api.py
-
-include Makefile.deps
-
-# These must be declared phony since there
-# are directories with matching names:
-.PHONY: api doc ext lib mac ref tut inst dist
-.PHONY: html info isilo
-
-
-# Main target
-default: html
-all: html dvi ps pdf isilo
-
-dvi: $(DVIFILES)
-pdf: $(PDFFILES)
-ps: $(PSFILES)
-
-world: ps pdf html distfiles
-
-
-# Rules to build PostScript and PDF formats
-.SUFFIXES: .dvi .ps
-
-.dvi.ps:
- $(DVIPS) -o $@ $<
-
-
-# Targets for each document:
-# Python/C API Reference Manual
-paper-$(PAPER)/api.dvi: $(ANNOAPIFILES)
- cd paper-$(PAPER) && $(MKDVI) api.tex
-
-paper-$(PAPER)/api.pdf: $(ANNOAPIFILES)
- cd paper-$(PAPER) && $(MKPDF) api.tex
-
-paper-$(PAPER)/api.tex: api/api.tex
- cp api/api.tex $@
-
-paper-$(PAPER)/abstract.tex: api/abstract.tex $(ANNOAPI)
- $(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/abstract.tex
-
-paper-$(PAPER)/concrete.tex: api/concrete.tex $(ANNOAPI)
- $(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/concrete.tex
-
-paper-$(PAPER)/exceptions.tex: api/exceptions.tex $(ANNOAPI)
- $(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/exceptions.tex
-
-paper-$(PAPER)/init.tex: api/init.tex $(ANNOAPI)
- $(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/init.tex
-
-paper-$(PAPER)/intro.tex: api/intro.tex
- cp api/intro.tex $@
-
-paper-$(PAPER)/memory.tex: api/memory.tex $(ANNOAPI)
- $(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/memory.tex
-
-paper-$(PAPER)/newtypes.tex: api/newtypes.tex $(ANNOAPI)
- $(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/newtypes.tex
-
-paper-$(PAPER)/refcounting.tex: api/refcounting.tex $(ANNOAPI)
- $(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/refcounting.tex
-
-paper-$(PAPER)/utilities.tex: api/utilities.tex $(ANNOAPI)
- $(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/utilities.tex
-
-paper-$(PAPER)/veryhigh.tex: api/veryhigh.tex $(ANNOAPI)
- $(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/veryhigh.tex
-
-# Distributing Python Modules
-paper-$(PAPER)/dist.dvi: $(DISTFILES)
- cd paper-$(PAPER) && $(MKDVI) ../dist/dist.tex
-
-paper-$(PAPER)/dist.pdf: $(DISTFILES)
- cd paper-$(PAPER) && $(MKPDF) ../dist/dist.tex
-
-# Documenting Python
-paper-$(PAPER)/doc.dvi: $(DOCFILES)
- cd paper-$(PAPER) && $(MKDVI) ../doc/doc.tex
-
-paper-$(PAPER)/doc.pdf: $(DOCFILES)
- cd paper-$(PAPER) && $(MKPDF) ../doc/doc.tex
-
-# Extending and Embedding the Python Interpreter
-paper-$(PAPER)/ext.dvi: $(EXTFILES)
- cd paper-$(PAPER) && $(MKDVI) ../ext/ext.tex
-
-paper-$(PAPER)/ext.pdf: $(EXTFILES)
- cd paper-$(PAPER) && $(MKPDF) ../ext/ext.tex
-
-# Installing Python Modules
-paper-$(PAPER)/inst.dvi: $(INSTFILES)
- cd paper-$(PAPER) && $(MKDVI) ../inst/inst.tex
-
-paper-$(PAPER)/inst.pdf: $(INSTFILES)
- cd paper-$(PAPER) && $(MKPDF) ../inst/inst.tex
-
-# Python Library Reference
-paper-$(PAPER)/lib.dvi: $(LIBFILES)
- cd paper-$(PAPER) && $(MKDVI) ../lib/lib.tex
-
-paper-$(PAPER)/lib.pdf: $(LIBFILES)
- cd paper-$(PAPER) && $(MKPDF) ../lib/lib.tex
-
-# Macintosh Library Modules
-paper-$(PAPER)/mac.dvi: $(MACFILES)
- cd paper-$(PAPER) && $(MKDVI) ../mac/mac.tex
-
-paper-$(PAPER)/mac.pdf: $(MACFILES)
- cd paper-$(PAPER) && $(MKPDF) ../mac/mac.tex
-
-# Python Reference Manual
-paper-$(PAPER)/ref.dvi: $(REFFILES)
- cd paper-$(PAPER) && $(MKDVI) ../ref/ref.tex
-
-paper-$(PAPER)/ref.pdf: $(REFFILES)
- cd paper-$(PAPER) && $(MKPDF) ../ref/ref.tex
-
-# Python Tutorial
-paper-$(PAPER)/tut.dvi: $(TUTFILES)
- cd paper-$(PAPER) && $(MKDVI) ../tut/tut.tex
-
-paper-$(PAPER)/tut.pdf: $(TUTFILES)
- cd paper-$(PAPER) && $(MKPDF) ../tut/tut.tex
-
-# What's New in Python X.Y
-paper-$(PAPER)/$(WHATSNEW).dvi: whatsnew/$(WHATSNEW).tex
- cd paper-$(PAPER) && $(MKDVI) ../whatsnew/$(WHATSNEW).tex
-
-paper-$(PAPER)/$(WHATSNEW).pdf: whatsnew/$(WHATSNEW).tex
- cd paper-$(PAPER) && $(MKPDF) ../whatsnew/$(WHATSNEW).tex
-
-# The remaining part of the Makefile is concerned with various
-# conversions, as described above. See also the README file.
-
-info:
- cd $(INFODIR) && $(MAKE) EMACS=$(EMACS)
-
-# Targets to convert the manuals to HTML using Nikos Drakos' LaTeX to
-# HTML converter. For more info on this program, see
-# .
-
-# Note that LaTeX2HTML inserts references to an icons directory in
-# each page that it generates. I have placed a copy of this directory
-# in the distribution to simplify the process of creating a
-# self-contained HTML distribution; for this purpose I have also added
-# a (trivial) index.html. Change the definition of $ICONSERVER in
-# perl/l2hinit.perl to use a different location for the icons directory.
-
-# If you have the standard LaTeX2HTML icons installed, the versions shipped
-# with this documentation should be stored in a separate directory and used
-# instead. The standard set does *not* include all the icons used in the
-# Python documentation.
-
-$(ALLCSSFILES): html/style.css
- cp $< $@
-
-$(INDEXFILES): $(COMMONPERL) html/stdabout.dat tools/node2label.pl
-
-html/acks.html: ACKS $(TOOLSDIR)/support.py $(TOOLSDIR)/mkackshtml
- $(PYTHON) $(TOOLSDIR)/mkackshtml --address $(PYTHONDOCS) \
- --favicon icons/pyfav.gif \
- --output html/acks.html $@
-
-html/modindex.html: $(TOOLSDIR)/support.py $(TOOLSDIR)/mkmodindex
-html/modindex.html: html/lib/lib.html html/mac/mac.html
- cd html && \
- $(PYTHON) ../$(TOOLSDIR)/mkmodindex --columns 4 \
- --output modindex.html --address $(PYTHONDOCS) \
- --favicon icons/pyfav.gif \
- lib/modindex.html mac/modindex.html
-
-html: $(ALLHTMLFILES) $(HTMLCSSFILES)
-
-api: html/api/api.html html/api/api.css
-html/api/api.html: $(APIFILES) api/refcounts.dat
- $(MKHTML) --dir html/api api/api.tex
-
-doc: html/doc/doc.html html/doc/doc.css
-html/doc/doc.html: $(DOCFILES)
- $(MKHTML) --dir html/doc doc/doc.tex
-
-ext: html/ext/ext.html html/ext/ext.css
-html/ext/ext.html: $(EXTFILES)
- $(MKHTML) --dir html/ext ext/ext.tex
-
-lib: html/lib/lib.html html/lib/lib.css
-html/lib/lib.html: $(LIBFILES)
- $(MKHTML) --dir html/lib lib/lib.tex
-
-mac: html/mac/mac.html html/mac/mac.css
-html/mac/mac.html: $(MACFILES)
- $(MKHTML) --dir html/mac mac/mac.tex
-
-ref: html/ref/ref.html html/ref/ref.css
-html/ref/ref.html: $(REFFILES)
- $(MKHTML) --dir html/ref ref/ref.tex
-
-tut: html/tut/tut.html html/tut/tut.css
-html/tut/tut.html: $(TUTFILES)
- $(MKHTML) --dir html/tut --numeric --split 3 tut/tut.tex
-
-inst: html/inst/inst.html html/inst/inst.css
-html/inst/inst.html: $(INSTFILES) perl/distutils.perl
- $(MKHTML) --dir html/inst --split 4 inst/inst.tex
-
-dist: html/dist/dist.html html/dist/dist.css
-html/dist/dist.html: $(DISTFILES) perl/distutils.perl
- $(MKHTML) --dir html/dist --split 4 dist/dist.tex
-
-whatsnew: html/whatsnew/$(WHATSNEW).html
-html/whatsnew/$(WHATSNEW).html: whatsnew/$(WHATSNEW).tex
- $(MKHTML) --dir html/whatsnew --split 4 whatsnew/$(WHATSNEW).tex
-
-
-# The iSilo format is used by the iSilo document reader for PalmOS devices.
-
-ISILOINDEXFILES=isilo/api/api.html \
- isilo/doc/doc.html \
- isilo/ext/ext.html \
- isilo/lib/lib.html \
- isilo/mac/mac.html \
- isilo/ref/ref.html \
- isilo/tut/tut.html \
- isilo/inst/inst.html \
- isilo/dist/dist.html \
- isilo/whatsnew/$(WHATSNEW).html
-
-$(ISILOINDEXFILES): $(COMMONPERL) html/stdabout.dat perl/isilo.perl
-
-isilo: isilo/python-api.pdb \
- isilo/python-doc.pdb \
- isilo/python-ext.pdb \
- isilo/python-lib.pdb \
- isilo/python-mac.pdb \
- isilo/python-ref.pdb \
- isilo/python-tut.pdb \
- isilo/python-dist.pdb \
- isilo/python-inst.pdb \
- isilo/python-whatsnew.pdb
-
-isilo/python-api.pdb: isilo/api/api.html isilo/api/api.css
- $(MKISILO) "-iPython/C API Reference Manual" \
- isilo/api/api.html $@
-
-isilo/python-doc.pdb: isilo/doc/doc.html isilo/doc/doc.css
- $(MKISILO) "-iDocumenting Python" \
- isilo/doc/doc.html $@
-
-isilo/python-ext.pdb: isilo/ext/ext.html isilo/ext/ext.css
- $(MKISILO) "-iExtending & Embedding Python" \
- isilo/ext/ext.html $@
-
-isilo/python-lib.pdb: isilo/lib/lib.html isilo/lib/lib.css
- $(MKISILO) "-iPython Library Reference" \
- isilo/lib/lib.html $@
-
-isilo/python-mac.pdb: isilo/mac/mac.html isilo/mac/mac.css
- $(MKISILO) "-iPython/C API Reference Manual" \
- isilo/mac/mac.html $@
-
-isilo/python-ref.pdb: isilo/ref/ref.html isilo/ref/ref.css
- $(MKISILO) "-iPython Reference Manual" \
- isilo/ref/ref.html $@
-
-isilo/python-tut.pdb: isilo/tut/tut.html isilo/tut/tut.css
- $(MKISILO) "-iPython Tutorial" \
- isilo/tut/tut.html $@
-
-isilo/python-dist.pdb: isilo/dist/dist.html isilo/dist/dist.css
- $(MKISILO) "-iDistributing Python Modules" \
- isilo/dist/dist.html $@
-
-isilo/python-inst.pdb: isilo/inst/inst.html isilo/inst/inst.css
- $(MKISILO) "-iInstalling Python Modules" \
- isilo/inst/inst.html $@
-
-isilo/python-whatsnew.pdb: isilo/whatsnew/$(WHATSNEW).html isilo/whatsnew/$(WHATSNEW).css
- $(MKISILO) "-iWhat's New in Python X.Y" \
- isilo/whatsnew/$(WHATSNEW).html $@
-
-isilo/api/api.html: $(APIFILES) api/refcounts.dat
- $(MKISILOHTML) --dir isilo/api api/api.tex
-
-isilo/doc/doc.html: $(DOCFILES)
- $(MKISILOHTML) --dir isilo/doc doc/doc.tex
-
-isilo/ext/ext.html: $(EXTFILES)
- $(MKISILOHTML) --dir isilo/ext ext/ext.tex
-
-isilo/lib/lib.html: $(LIBFILES)
- $(MKISILOHTML) --dir isilo/lib lib/lib.tex
-
-isilo/mac/mac.html: $(MACFILES)
- $(MKISILOHTML) --dir isilo/mac mac/mac.tex
-
-isilo/ref/ref.html: $(REFFILES)
- $(MKISILOHTML) --dir isilo/ref ref/ref.tex
-
-isilo/tut/tut.html: $(TUTFILES)
- $(MKISILOHTML) --dir isilo/tut tut/tut.tex
-
-isilo/inst/inst.html: $(INSTFILES) perl/distutils.perl
- $(MKISILOHTML) --dir isilo/inst inst/inst.tex
-
-isilo/dist/dist.html: $(DISTFILES) perl/distutils.perl
- $(MKISILOHTML) --dir isilo/dist dist/dist.tex
-
-isilo/whatsnew/$(WHATSNEW).html: whatsnew/$(WHATSNEW).tex
- $(MKISILOHTML) --dir isilo/whatsnew whatsnew/$(WHATSNEW).tex
-
-# These are useful if you need to transport the iSilo-ready HTML to
-# another machine to perform the conversion:
-
-isilozip: isilo-html-$(RELEASE).zip
-
-isilo-html-$(RELEASE).zip: $(ISILOINDEXFILES)
- rm -f $@
- cd isilo && \
- zip -q -9 ../$@ */*.css */*.html */*.txt
-
-
-# webchecker needs an extra flag to process the huge index from the libref
-WEBCHECKER=$(PYTHON) ../Tools/webchecker/webchecker.py
-HTMLBASE= file:`pwd`/html
-
-webcheck: $(ALLHTMLFILES)
- $(WEBCHECKER) $(HTMLBASE)/api/
- $(WEBCHECKER) $(HTMLBASE)/doc/
- $(WEBCHECKER) $(HTMLBASE)/ext/
- $(WEBCHECKER) -m290000 $(HTMLBASE)/lib/
- $(WEBCHECKER) $(HTMLBASE)/mac/
- $(WEBCHECKER) $(HTMLBASE)/ref/
- $(WEBCHECKER) $(HTMLBASE)/tut/
- $(WEBCHECKER) $(HTMLBASE)/dist/
- $(WEBCHECKER) $(HTMLBASE)/inst/
- $(WEBCHECKER) $(HTMLBASE)/whatsnew/
-
-fastwebcheck: $(ALLHTMLFILES)
- $(WEBCHECKER) -x $(HTMLBASE)/api/
- $(WEBCHECKER) -x $(HTMLBASE)/doc/
- $(WEBCHECKER) -x $(HTMLBASE)/ext/
- $(WEBCHECKER) -x -m290000 $(HTMLBASE)/lib/
- $(WEBCHECKER) -x $(HTMLBASE)/mac/
- $(WEBCHECKER) -x $(HTMLBASE)/ref/
- $(WEBCHECKER) -x $(HTMLBASE)/tut/
- $(WEBCHECKER) -x $(HTMLBASE)/dist/
- $(WEBCHECKER) -x $(HTMLBASE)/inst/
- $(WEBCHECKER) -x $(HTMLBASE)/whatsnew/
-
-
-# Release packaging targets:
-
-paper-$(PAPER)/README: $(PSFILES) $(TOOLSDIR)/getpagecounts
- cd paper-$(PAPER) && ../$(TOOLSDIR)/getpagecounts -r $(RELEASE) >../$@
-
-info-$(RELEASE).tgz: info
- cd $(INFODIR) && tar cf - README python.dir python-*.info* \
- | gzip -9 >$@
-
-info-$(RELEASE).tar.bz2: info
- cd $(INFODIR) && tar cf - README python.dir python-*.info* \
- | bzip2 -9 >$@
-
-latex-$(RELEASE).tgz:
- $(PYTHON) $(TOOLSDIR)/mksourcepkg --gzip $(RELEASE)
-
-latex-$(RELEASE).tar.bz2:
- $(PYTHON) $(TOOLSDIR)/mksourcepkg --bzip2 $(RELEASE)
-
-latex-$(RELEASE).zip:
- rm -f $@
- $(PYTHON) $(TOOLSDIR)/mksourcepkg --zip $(RELEASE)
-
-pdf-$(PAPER)-$(RELEASE).tar: $(PDFFILES)
- rm -f $@
- mkdir Python-Docs-$(RELEASE)
- cp paper-$(PAPER)/*.pdf Python-Docs-$(RELEASE)
- tar cf $@ Python-Docs-$(RELEASE)
- rm -r Python-Docs-$(RELEASE)
-
-pdf-$(PAPER)-$(RELEASE).tgz: pdf-$(PAPER)-$(RELEASE).tar
- gzip -9 <$? >$@
-
-pdf-$(PAPER)-$(RELEASE).tar.bz2: pdf-$(PAPER)-$(RELEASE).tar
- bzip2 -9 <$? >$@
-
-pdf-$(PAPER)-$(RELEASE).zip: pdf
- rm -f $@
- mkdir Python-Docs-$(RELEASE)
- cp paper-$(PAPER)/*.pdf Python-Docs-$(RELEASE)
- zip -q -r -9 $@ Python-Docs-$(RELEASE)
- rm -r Python-Docs-$(RELEASE)
-
-postscript-$(PAPER)-$(RELEASE).tar: $(PSFILES) paper-$(PAPER)/README
- rm -f $@
- mkdir Python-Docs-$(RELEASE)
- cp paper-$(PAPER)/*.ps Python-Docs-$(RELEASE)
- cp paper-$(PAPER)/README Python-Docs-$(RELEASE)
- tar cf $@ Python-Docs-$(RELEASE)
- rm -r Python-Docs-$(RELEASE)
-
-postscript-$(PAPER)-$(RELEASE).tar.bz2: postscript-$(PAPER)-$(RELEASE).tar
- bzip2 -9 <$< >$@
-
-postscript-$(PAPER)-$(RELEASE).tgz: postscript-$(PAPER)-$(RELEASE).tar
- gzip -9 <$< >$@
-
-postscript-$(PAPER)-$(RELEASE).zip: $(PSFILES) paper-$(PAPER)/README
- rm -f $@
- mkdir Python-Docs-$(RELEASE)
- cp paper-$(PAPER)/*.ps Python-Docs-$(RELEASE)
- cp paper-$(PAPER)/README Python-Docs-$(RELEASE)
- zip -q -r -9 $@ Python-Docs-$(RELEASE)
- rm -r Python-Docs-$(RELEASE)
-
-HTMLPKGFILES=*.html */*.css */*.html */*.gif */*.txt
-
-html-$(RELEASE).tar: $(ALLHTMLFILES) $(HTMLCSSFILES)
- mkdir Python-Docs-$(RELEASE)
- cd html && tar cf ../temp.tar $(HTMLPKGFILES)
- cd Python-Docs-$(RELEASE) && tar xf ../temp.tar
- rm temp.tar
- tar cf html-$(RELEASE).tar Python-Docs-$(RELEASE)
- rm -r Python-Docs-$(RELEASE)
-
-html-$(RELEASE).tgz: html-$(RELEASE).tar
- gzip -9 <$? >$@
-
-html-$(RELEASE).tar.bz2: html-$(RELEASE).tar
- bzip2 -9 <$? >$@
-
-html-$(RELEASE).zip: $(ALLHTMLFILES) $(HTMLCSSFILES)
- rm -f $@
- mkdir Python-Docs-$(RELEASE)
- cd html && tar cf ../temp.tar $(HTMLPKGFILES)
- cd Python-Docs-$(RELEASE) && tar xf ../temp.tar
- rm temp.tar
- zip -q -r -9 $@ Python-Docs-$(RELEASE)
- rm -r Python-Docs-$(RELEASE)
-
-isilo-$(RELEASE).zip: isilo
- rm -f $@
- mkdir Python-Docs-$(RELEASE)
- cp isilo/python-*.pdb Python-Docs-$(RELEASE)
- zip -q -r -9 $@ Python-Docs-$(RELEASE)
- rm -r Python-Docs-$(RELEASE)
-
-
-# convenience targets:
-
-tarhtml: html-$(RELEASE).tgz
-tarinfo: info-$(RELEASE).tgz
-tarps: postscript-$(PAPER)-$(RELEASE).tgz
-tarpdf: pdf-$(PAPER)-$(RELEASE).tgz
-tarlatex: latex-$(RELEASE).tgz
-
-tarballs: tarpdf tarps tarhtml
-
-ziphtml: html-$(RELEASE).zip
-zipps: postscript-$(PAPER)-$(RELEASE).zip
-zippdf: pdf-$(PAPER)-$(RELEASE).zip
-ziplatex: latex-$(RELEASE).zip
-zipisilo: isilo-$(RELEASE).zip
-
-zips: zippdf zipps ziphtml
-
-bziphtml: html-$(RELEASE).tar.bz2
-bzipinfo: info-$(RELEASE).tar.bz2
-bzipps: postscript-$(PAPER)-$(RELEASE).tar.bz2
-bzippdf: pdf-$(PAPER)-$(RELEASE).tar.bz2
-bziplatex: latex-$(RELEASE).tar.bz2
-
-bzips: bzippdf bzipps bziphtml
-
-disthtml: tarhtml bziphtml ziphtml
-distinfo: tarinfo bzipinfo
-distps: tarps bzipps zipps
-distpdf: tarpdf bzippdf zippdf
-distlatex: tarlatex bziplatex ziplatex
-
-paperdist: distpdf distps
-edist: disthtml zipisilo
-
-distfiles: paperdist edist
- $(TOOLSDIR)/mksourcepkg --all $(RELEASE)
- $(TOOLSDIR)/mkpkglist >pkglist.html
-
-
-# Housekeeping targets
-
-# Remove temporary files; all except the following:
-# - sources: .tex, .bib, .sty, *.cls
-# - useful results: .dvi, .pdf, .ps, .texi, .info
-clean:
- rm -f html-$(RELEASE).tar
- cd $(INFODIR) && $(MAKE) clean
-
-# Remove temporaries as well as final products
-clobber:
- rm -f html-$(RELEASE).tar
- rm -f html-$(RELEASE).tgz info-$(RELEASE).tgz
- rm -f pdf-$(RELEASE).tgz postscript-$(RELEASE).tgz
- rm -f latex-$(RELEASE).tgz html-$(RELEASE).zip
- rm -f pdf-$(RELEASE).zip postscript-$(RELEASE).zip
- rm -f $(DVIFILES) $(PSFILES) $(PDFFILES)
- cd $(INFODIR) && $(MAKE) clobber
- rm -f paper-$(PAPER)/*.tex paper-$(PAPER)/*.ind paper-$(PAPER)/*.idx
- rm -f paper-$(PAPER)/*.l2h paper-$(PAPER)/*.how paper-$(PAPER)/README
- rm -rf html/index.html html/modindex.html html/acks.html
- rm -rf html/api/ html/doc/ html/ext/ html/lib/ html/mac/
- rm -rf html/ref/ html/tut/ html/inst/ html/dist/
- rm -rf html/whatsnew/
- rm -rf isilo/api/ isilo/doc/ isilo/ext/ isilo/lib/ isilo/mac/
- rm -rf isilo/ref/ isilo/tut/ isilo/inst/ isilo/dist/
- rm -rf isilo/whatsnew/
- rm -f isilo/python-*.pdb isilo-$(RELEASE).zip
-
-realclean distclean: clobber
diff --git a/Doc/Makefile.deps b/Doc/Makefile.deps
deleted file mode 100644
index 55d8de0b6a..0000000000
--- a/Doc/Makefile.deps
+++ /dev/null
@@ -1,373 +0,0 @@
-# LaTeX source dependencies.
-
-COMMONSTYLES= texinputs/python.sty \
- texinputs/pypaper.sty
-
-INDEXSTYLES=texinputs/python.ist
-
-COMMONTEX= texinputs/copyright.tex \
- texinputs/license.tex \
- texinputs/boilerplate.tex
-
-MANSTYLES= texinputs/fncychap.sty \
- texinputs/manual.cls \
- $(COMMONSTYLES)
-
-HOWTOSTYLES= texinputs/howto.cls \
- $(COMMONSTYLES)
-
-
-APIFILES= $(MANSTYLES) $(INDEXSTYLES) $(COMMONTEX) \
- api/api.tex \
- api/abstract.tex \
- api/concrete.tex \
- api/exceptions.tex \
- api/init.tex \
- api/intro.tex \
- api/memory.tex \
- api/newtypes.tex \
- api/refcounting.tex \
- api/utilities.tex \
- api/veryhigh.tex \
- texinputs/typestruct.h \
- texinputs/reportingbugs.tex
-
-# These files are generated from those listed above, and are used to
-# generate the typeset versions of the manuals. The list is defined
-# here to make it easier to ensure parallelism.
-ANNOAPIFILES= $(MANSTYLES) $(INDEXSTYLES) $(COMMONTEX) api/refcounts.dat \
- paper-$(PAPER)/api.tex \
- paper-$(PAPER)/abstract.tex \
- paper-$(PAPER)/concrete.tex \
- paper-$(PAPER)/exceptions.tex \
- paper-$(PAPER)/init.tex \
- paper-$(PAPER)/intro.tex \
- paper-$(PAPER)/memory.tex \
- paper-$(PAPER)/newtypes.tex \
- paper-$(PAPER)/refcounting.tex \
- paper-$(PAPER)/utilities.tex \
- paper-$(PAPER)/veryhigh.tex \
- texinputs/reportingbugs.tex
-
-DOCFILES= $(HOWTOSTYLES) \
- texinputs/boilerplate.tex \
- texinputs/ltxmarkup.sty \
- doc/doc.tex
-
-EXTFILES= ext/ext.tex $(MANSTYLES) $(INDEXSTYLES) $(COMMONTEX) \
- ext/extending.tex \
- ext/newtypes.tex \
- ext/building.tex \
- ext/windows.tex \
- ext/embedding.tex \
- ext/cycle-gc.c \
- ext/noddy.c \
- ext/run-func.c \
- texinputs/typestruct.h \
- texinputs/reportingbugs.tex
-
-TUTFILES= tut/tut.tex $(MANSTYLES) $(COMMONTEX)
-
-# LaTeX source files for the Python Reference Manual
-REFFILES= $(MANSTYLES) $(INDEXSTYLES) $(COMMONTEX) \
- ref/ref.tex \
- ref/ref1.tex \
- ref/ref2.tex \
- ref/ref3.tex \
- ref/ref4.tex \
- ref/ref5.tex \
- ref/ref6.tex \
- ref/ref7.tex \
- ref/ref8.tex
-
-# LaTeX source files for the Python Library Reference
-LIBFILES= $(MANSTYLES) $(INDEXSTYLES) $(COMMONTEX) \
- texinputs/reportingbugs.tex \
- lib/lib.tex \
- lib/asttable.tex \
- lib/compiler.tex \
- lib/distutils.tex \
- lib/email.tex \
- lib/emailencoders.tex \
- lib/emailexc.tex \
- lib/emailgenerator.tex \
- lib/emailiter.tex \
- lib/emailmessage.tex \
- lib/emailparser.tex \
- lib/emailutil.tex \
- lib/libintro.tex \
- lib/libobjs.tex \
- lib/libstdtypes.tex \
- lib/libexcs.tex \
- lib/libconsts.tex \
- lib/libfuncs.tex \
- lib/libpython.tex \
- lib/libsys.tex \
- lib/libfpectl.tex \
- lib/libgc.tex \
- lib/libsets.tex \
- lib/libweakref.tex \
- lib/libinspect.tex \
- lib/libpydoc.tex \
- lib/libdifflib.tex \
- lib/libdoctest.tex \
- lib/libunittest.tex \
- lib/libtypes.tex \
- lib/libtraceback.tex \
- lib/libpickle.tex \
- lib/libshelve.tex \
- lib/libcopy.tex \
- lib/libmarshal.tex \
- lib/libwarnings.tex \
- lib/libimp.tex \
- lib/libpkgutil.tex \
- lib/libparser.tex \
- lib/libbltin.tex \
- lib/libmain.tex \
- lib/libfuture.tex \
- lib/libstrings.tex \
- lib/libstring.tex \
- lib/libtextwrap.tex \
- lib/libcodecs.tex \
- lib/libunicodedata.tex \
- lib/libstringprep.tex \
- lib/libstruct.tex \
- lib/libmisc.tex \
- lib/libmath.tex \
- lib/librand.tex \
- lib/libwhrandom.tex \
- lib/libarray.tex \
- lib/liballos.tex \
- lib/libos.tex \
- lib/libdatetime.tex \
- lib/tzinfo-examples.py \
- lib/libtime.tex \
- lib/libgetopt.tex \
- lib/liboptparse.tex \
- lib/caseless.py \
- lib/required_1.py \
- lib/required_2.py \
- lib/libtempfile.tex \
- lib/liberrno.tex \
- lib/libsomeos.tex \
- lib/libsignal.tex \
- lib/libsocket.tex \
- lib/libselect.tex \
- lib/libthread.tex \
- lib/libdummythread.tex \
- lib/libunix.tex \
- lib/libposix.tex \
- lib/libposixpath.tex \
- lib/libpwd.tex \
- lib/libgrp.tex \
- lib/libcrypt.tex \
- lib/libdbm.tex \
- lib/libgdbm.tex \
- lib/libtermios.tex \
- lib/libfcntl.tex \
- lib/libposixfile.tex \
- lib/libsyslog.tex \
- lib/liblogging.tex \
- lib/libpdb.tex \
- lib/libprofile.tex \
- lib/libhotshot.tex \
- lib/libtimeit.tex \
- lib/libcgi.tex \
- lib/libcgitb.tex \
- lib/liburllib.tex \
- lib/liburllib2.tex \
- lib/libhttplib.tex \
- lib/libftplib.tex \
- lib/libgopherlib.tex \
- lib/libnntplib.tex \
- lib/liburlparse.tex \
- lib/libhtmlparser.tex \
- lib/libhtmllib.tex \
- lib/libsgmllib.tex \
- lib/librfc822.tex \
- lib/libmimetools.tex \
- lib/libmimewriter.tex \
- lib/libbinascii.tex \
- lib/libmm.tex \
- lib/libaudioop.tex \
- lib/libimageop.tex \
- lib/libaifc.tex \
- lib/libjpeg.tex \
- lib/librgbimg.tex \
- lib/libossaudiodev.tex \
- lib/libcrypto.tex \
- lib/libmd5.tex \
- lib/libsha.tex \
- lib/libmpz.tex \
- lib/libhmac.tex \
- lib/librotor.tex \
- lib/libstdwin.tex \
- lib/libsgi.tex \
- lib/libal.tex \
- lib/libcd.tex \
- lib/libfl.tex \
- lib/libfm.tex \
- lib/libgl.tex \
- lib/libimgfile.tex \
- lib/libsun.tex \
- lib/libxdrlib.tex \
- lib/libimghdr.tex \
- lib/librestricted.tex \
- lib/librexec.tex \
- lib/libbastion.tex \
- lib/libformatter.tex \
- lib/liboperator.tex \
- lib/libresource.tex \
- lib/libstat.tex \
- lib/libstringio.tex \
- lib/libtoken.tex \
- lib/libkeyword.tex \
- lib/libundoc.tex \
- lib/libmailcap.tex \
- lib/libglob.tex \
- lib/libuser.tex \
- lib/libanydbm.tex \
- lib/libbsddb.tex \
- lib/libdbhash.tex \
- lib/librandom.tex \
- lib/libsite.tex \
- lib/libwhichdb.tex \
- lib/libbase64.tex \
- lib/libfnmatch.tex \
- lib/libquopri.tex \
- lib/libzlib.tex \
- lib/libsocksvr.tex \
- lib/libmailbox.tex \
- lib/libcommands.tex \
- lib/libcmath.tex \
- lib/libgzip.tex \
- lib/libbz2.tex \
- lib/libzipfile.tex \
- lib/libpprint.tex \
- lib/libcode.tex \
- lib/libmimify.tex \
- lib/libre.tex \
- lib/libuserdict.tex \
- lib/libdis.tex \
- lib/libxmllib.tex \
- lib/libxmlrpclib.tex \
- lib/libsimplexmlrpc.tex \
- lib/libdocxmlrpc.tex \
- lib/libpyexpat.tex \
- lib/xmldom.tex \
- lib/xmldomminidom.tex \
- lib/xmldompulldom.tex \
- lib/xmlsax.tex \
- lib/xmlsaxhandler.tex \
- lib/xmlsaxutils.tex \
- lib/xmlsaxreader.tex \
- lib/libqueue.tex \
- lib/liblocale.tex \
- lib/libgettext.tex \
- lib/libbasehttp.tex \
- lib/libcookie.tex \
- lib/libcopyreg.tex \
- lib/libsymbol.tex \
- lib/libbinhex.tex \
- lib/libuu.tex \
- lib/libsunaudio.tex \
- lib/libfileinput.tex \
- lib/libxreadlines.tex \
- lib/libimaplib.tex \
- lib/libpoplib.tex \
- lib/libcalendar.tex \
- lib/libpopen2.tex \
- lib/libbisect.tex \
- lib/libheapq.tex \
- lib/libmimetypes.tex \
- lib/libsmtplib.tex \
- lib/libcmd.tex \
- lib/libmultifile.tex \
- lib/libthreading.tex \
- lib/libdummythreading.tex \
- lib/libwebbrowser.tex \
- lib/internet.tex \
- lib/netdata.tex \
- lib/markup.tex \
- lib/language.tex \
- lib/libpycompile.tex \
- lib/libcompileall.tex \
- lib/libshlex.tex \
- lib/libnetrc.tex \
- lib/librobotparser.tex \
- lib/libgetpass.tex \
- lib/libshutil.tex \
- lib/librepr.tex \
- lib/libmsvcrt.tex \
- lib/libwinreg.tex \
- lib/libwinsound.tex \
- lib/windows.tex \
- lib/libpyclbr.tex \
- lib/libtokenize.tex \
- lib/libtabnanny.tex \
- lib/libmhlib.tex \
- lib/libtelnetlib.tex \
- lib/libcolorsys.tex \
- lib/libfpformat.tex \
- lib/libcgihttp.tex \
- lib/libsimplehttp.tex \
- lib/liblinecache.tex \
- lib/libnew.tex \
- lib/libdircache.tex \
- lib/libfilecmp.tex \
- lib/libstatcache.tex \
- lib/libsunau.tex \
- lib/libwave.tex \
- lib/libchunk.tex \
- lib/libcodeop.tex \
- lib/libcurses.tex \
- lib/libcursespanel.tex \
- lib/libascii.tex \
- lib/libdl.tex \
- lib/libmutex.tex \
- lib/libnis.tex \
- lib/libpipes.tex \
- lib/libpty.tex \
- lib/libreadline.tex \
- lib/librlcompleter.tex \
- lib/libsched.tex \
- lib/libstatvfs.tex \
- lib/libtty.tex \
- lib/libasyncore.tex \
- lib/libasynchat.tex \
- lib/libatexit.tex \
- lib/libmmap.tex \
- lib/tkinter.tex \
- lib/libturtle.tex \
- lib/libtarfile.tex \
- lib/libcsv.tex \
- lib/libcfgparser.tex
-
-# LaTeX source files for Macintosh Library Modules.
-MACFILES= $(HOWTOSTYLES) $(INDEXSTYLES) $(COMMONTEX) \
- mac/mac.tex \
- mac/using.tex \
- mac/scripting.tex \
- mac/toolbox.tex \
- mac/undoc.tex \
- mac/libcolorpicker.tex \
- mac/libmac.tex \
- mac/libgensuitemodule.tex \
- mac/libaetools.tex \
- mac/libaepack.tex \
- mac/libaetypes.tex \
- mac/libmacfs.tex \
- mac/libmacos.tex \
- mac/libmacostools.tex \
- mac/libmacui.tex \
- mac/libmacic.tex \
- mac/libframework.tex \
- mac/libautogil.tex \
- mac/libminiae.tex \
- mac/libscrap.tex
-
-INSTFILES = $(HOWTOSTYLES) inst/inst.tex
-
-DISTFILES = $(HOWTOSTYLES) \
- dist/dist.tex \
- dist/sysconfig.tex
diff --git a/Doc/README b/Doc/README
deleted file mode 100644
index aee8fb6b9e..0000000000
--- a/Doc/README
+++ /dev/null
@@ -1,231 +0,0 @@
-Python standard documentation -- in LaTeX
------------------------------------------
-
-This directory contains the LaTeX sources to the Python documentation
-and tools required to support the formatting process. The documents
-now require LaTeX2e; LaTeX 2.09 compatibility has been dropped.
-
-If you don't have LaTeX, or if you'd rather not format the
-documentation yourself, you can ftp a tar file containing HTML, PDF,
-or PostScript versions of all documents. Additional formats may be
-available. These should be in the same place where you fetched the
-main Python distribution (try or
-).
-
-The following are the LaTeX source files:
-
- api/*.tex Python/C API Reference Manual
- doc/*.tex Documenting Python
- ext/*.tex Extending and Embedding the Python Interpreter
- lib/*.tex Python Library Reference
- mac/*.tex Macintosh Library Modules
- ref/*.tex Python Reference Manual
- tut/*.tex Python Tutorial
- inst/*.tex Installing Python Modules
- dist/*.tex Distributing Python Modules
-
-Most use the "manual" document class and "python" package, derived from
-the old "myformat.sty" style file. The Macintosh Library Modules
-document uses the "howto" document class instead. These contains many
-macro definitions useful in documenting Python, and set some style
-parameters.
-
-There's a Makefile to call LaTeX and the other utilities in the right
-order and the right number of times. By default, it will build the
-HTML version of the documnetation, but DVI, PDF, and PostScript can
-also be made. To view the generated HTML, point your favorite browser
-at the top-level index (html/index.html) after running "make".
-
-The Makefile can also produce DVI files for each document made; to
-preview them, use xdvi. PostScript is produced by the same Makefile
-target that produces the DVI files. This uses the dvips tool.
-Printing depends on local conventions; at our site, we use lpr. For
-example:
-
- make paper-letter/lib.ps # create lib.dvi and lib.ps
- xdvi paper-letter/lib.dvi # preview lib.dvi
- lpr paper-letter/lib.ps # print on default printer
-
-
-What if I find a bug?
----------------------
-
-First, check that the bug is present in the development version of the
-documentation at ; we may
-have already fixed it.
-
-If we haven't, tell us about it. We'd like the documentation to be
-complete and accurate, but have limited time. If you discover any
-inconsistencies between the documentation and implementation, or just
-have suggestions as to how to improve the documentation, let is know!
-Specific bugs and patches should be reported using our bug & patch
-databases at:
-
- http://sourceforge.net/projects/python
-
-Other suggestions or questions should be sent to the Python
-Documentation Team:
-
- python-docs@python.org
-
-Thanks!
-
-
-What happened to the Macintosh chapter of the Python Library Reference?
------------------------------------------------------------------------
-
-The directory mac/ contains the LaTeX sources for the "Macintosh
-Library Modules" manual; this is built using the standard build
-targets, so check the proper output directory for your chosen format
-and paper size.
-
-
-What tools do I need?
----------------------
-
-You need to install Python; some of the scripts used to produce the
-documentation are written in Python. You don't need this
-documentation to install Python; instructions are included in the
-README file in the Python distribution.
-
-The simplest way to get the rest of the tools in the configuration we
-used is to install the teTeX TeX distribution, versions 0.9 or newer.
-More information is available on teTeX at .
-This is a Unix-only TeX distribution at this time. This documentation
-release was tested with the 1.0.7 release, but there have been no
-substantial changes since late in the 0.9 series, which we used
-extensively for previous versions without any difficulty.
-
-If you don't want to get teTeX, here is what you'll need:
-
-To create DVI, PDF, or PostScript files:
-
- - LaTeX2e, 1995/12/01 or newer. Older versions are likely to
- choke.
-
- - makeindex. This is used to produce the indexes for the
- library reference and Python/C API reference.
-
-To create PDF files:
-
- - pdflatex. We used the one in the teTeX distribution (pdfTeX
- version 3.14159-13d (Web2C 7.3.1) at the time of this
- writing). Versions even a couple of patchlevels earlier are
- highly likely to fail due to syntax changes for some of the
- pdftex primitives.
-
-To create PostScript files:
-
- - dvips. Most TeX installations include this. If you don't
- have one, check CTAN ().
-
-To create info files:
-
- Note that info support is currently being revised using new
- conversion tools by Michael Ernst .
-
- - makeinfo. This is available from any GNU mirror.
-
- - emacs or xemacs. Emacs is available from the same place as
- makeinfo, and xemacs is available from ftp.xemacs.org.
-
- - Perl. Find the software at
- .
-
- - HTML::Element. If you don't have this installed, you can get
- this from CPAN. Use the command:
-
- perl -e 'use CPAN; CPAN::install("HTML::Element");'
-
- You may need to be root to do this.
-
-To create HTML files:
-
- - Perl 5.004_04 or newer. Find the software at
- .
-
- - LaTeX2HTML 99.2b8 or newer. Older versions are not
- supported; each version changes enough that supporting
- multiple versions is not likely to work. Many older
- versions don't work with Perl 5.6 as well. This also screws
- up code fragments. ;-( Releases are available at:
- .
-
-
-What if Times fonts are not available?
---------------------------------------
-
-As distributed, the LaTeX documents use PostScript Times fonts. This
-is done since they are much better looking and produce smaller
-PostScript files. If, however, your TeX installation does not support
-them, they may be easily disabled. Edit the file
-texinputs/pypaper.sty and comment out the line that starts
-"\RequirePackage{times}" by inserting a "%" character at the beginning
-of the line. If you're formatting the docs for A4 paper instead of
-US-Letter paper, change paper-a4/pypaper.sty instead. An alternative
-is to install the right fonts and LaTeX style file.
-
-
-What if I want to use A4 paper?
--------------------------------
-
-Instead of building the PostScript by giving the command "make ps",
-give the command "make PAPER=a4 ps"; the output will be produced in
-the paper-a4/ subdirectory. (You can use "make PAPER=a4 pdf" if you'd
-rather have PDF output.)
-
-
-Making HTML files
------------------
-
-The LaTeX documents can be converted to HTML using Nikos Drakos'
-LaTeX2HTML converter. See the Makefile; after some twiddling, "make"
-should do the trick.
-
-
-What else is in here?
----------------------
-
-There is a new LaTeX document class called "howto". This is used for
-the new series of Python HOWTO documents which is being coordinated by
-Andrew Kuchling . The file
-templates/howto.tex is a commented example which may be used as a
-template. A Python script to "do the right thing" to format a howto
-document is included as tools/mkhowto. These documents can be
-formatted as HTML, PDF, PostScript, or ASCII files. Use "mkhowto
---help" for information on using the formatting tool.
-
-For authors of module documentation, there is a file
-templates/module.tex which may be used as a template for a module
-section. This may be used in conjunction with either the howto or
-manual document class. Create the documentation for a new module by
-copying the template to lib.tex and editing according to the
-instructions in the comments.
-
-Documentation on the authoring Python documentation, including
-information about both style and markup, is available in the
-"Documenting Python" manual.
-
-
-Copyright notice
-================
-
-The Python source is copyrighted, but you can freely use and copy it
-as long as you don't change or remove the copyright notice:
-
-----------------------------------------------------------------------
-Copyright (c) 2000-2002 Python Software Foundation.
-All rights reserved.
-
-Copyright (c) 2000 BeOpen.com.
-All rights reserved.
-
-Copyright (c) 1995-2000 Corporation for National Research Initiatives.
-All rights reserved.
-
-Copyright (c) 1991-1995 Stichting Mathematisch Centrum.
-All rights reserved.
-
-See the file "texinputs/license.tex" for information on usage and
-redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-----------------------------------------------------------------------
diff --git a/Doc/TODO b/Doc/TODO
deleted file mode 100644
index 8a467fe0a8..0000000000
--- a/Doc/TODO
+++ /dev/null
@@ -1,74 +0,0 @@
-PYTHON DOCUMENTATION TO-DO LIST -*- indented-text -*-
-===============================
-
-General
--------
-
-* Figure out HTMLHelp generation for the Windows world.
-
-
-Python/C API
-------------
-
-* The "Very High Level Interface" in the API document has been
- requested; I guess it wouldn't hurt to fill in a bit there. Request
- by Albert Hofkamp . (Partly done.)
-
-* Describe implementing types in C, including use of the 'self'
- parameter to the method implementation function. (Missing material
- mentioned in the Extending & Embedding manual, section 1.1; problem
- reported by Clay Spence .) Heavily impacts one
- chapter of the Python/C API manual.
-
-* Missing PyArg_ParseTuple(), PyArg_ParseTupleAndKeywords(),
- Py_BuildValue(). Information requested by Greg Kochanski
- . PyEval_EvalCode() has also been requested.
-
-Extending & Embedding
----------------------
-
-* More information is needed about building dynamically linked
- extensions in C++. Specifically, the extensions must be linked
- against the C++ libraries (and possibly runtime). Also noted by
- Albert Hofkamp .
-
-Reference Manual
-----------------
-
-* Document the Extended Call Syntax in the language reference.
- [Jeremy Hylton]
-
-* Document new comparison support for recursive objects (lang. ref.?
- library ref.? (cmp() function). [Jeremy Hylton]
-
-Library Reference
------------------
-
-* Update the pickle documentation to describe all of the current
- behavior; only a subset is described. __reduce__, etc. Partial
- update submitted by Jim Kerr .
-
-* Update the httplib documentation to match Greg Stein's HTTP/1.1
- support and new classes. (Greg, this is yours!)
-
-Tutorial
---------
-
-* Update tutorial to use string methods and talk about backward
- compatibility of same.
-
-
-NOT WORTH THE TROUBLE
----------------------
-
-* In the indexes, some subitem entries are separated from the item
- entries by column- or page-breaks. Reported by Lorenzo M. Catucci
- . This one will be hard; probably not
- really worth the pain. (Only an issue at all when a header-letter
- and the first index entry get separated -- can change as soon as we
- change the index entries in the text.) Also only a problem in the
- print version.
-
-* Fix problem with howto documents getting the last module synopsis
- twice (in \localmoduletable) so we can get rid of the ugly 'uniq'
- hack in tools/mkhowto. (Probably not worth the trouble of fixing.)
diff --git a/Doc/api/.cvsignore b/Doc/api/.cvsignore
deleted file mode 100644
index ea4fca3aac..0000000000
--- a/Doc/api/.cvsignore
+++ /dev/null
@@ -1,3 +0,0 @@
-*.esis
-*.esis1
-*.xml
diff --git a/Doc/api/abstract.tex b/Doc/api/abstract.tex
deleted file mode 100644
index dd237683f6..0000000000
--- a/Doc/api/abstract.tex
+++ /dev/null
@@ -1,1020 +0,0 @@
-\chapter{Abstract Objects Layer \label{abstract}}
-
-The functions in this chapter interact with Python objects regardless
-of their type, or with wide classes of object types (e.g. all
-numerical types, or all sequence types). When used on object types
-for which they do not apply, they will raise a Python exception.
-
-
-\section{Object Protocol \label{object}}
-
-\begin{cfuncdesc}{int}{PyObject_Print}{PyObject *o, FILE *fp, int flags}
- Print an object \var{o}, on file \var{fp}. Returns \code{-1} on
- error. The flags argument is used to enable certain printing
- options. The only option currently supported is
- \constant{Py_PRINT_RAW}; if given, the \function{str()} of the
- object is written instead of the \function{repr()}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyObject_HasAttrString}{PyObject *o, char *attr_name}
- Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
- \code{0} otherwise. This is equivalent to the Python expression
- \samp{hasattr(\var{o}, \var{attr_name})}. This function always
- succeeds.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyObject_GetAttrString}{PyObject *o,
- char *attr_name}
- Retrieve an attribute named \var{attr_name} from object \var{o}.
- Returns the attribute value on success, or \NULL{} on failure.
- This is the equivalent of the Python expression
- \samp{\var{o}.\var{attr_name}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyObject_HasAttr}{PyObject *o, PyObject *attr_name}
- Returns \code{1} if \var{o} has the attribute \var{attr_name}, and
- \code{0} otherwise. This is equivalent to the Python expression
- \samp{hasattr(\var{o}, \var{attr_name})}. This function always
- succeeds.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyObject_GetAttr}{PyObject *o,
- PyObject *attr_name}
- Retrieve an attribute named \var{attr_name} from object \var{o}.
- Returns the attribute value on success, or \NULL{} on failure. This
- is the equivalent of the Python expression
- \samp{\var{o}.\var{attr_name}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyObject_SetAttrString}{PyObject *o,
- char *attr_name, PyObject *v}
- Set the value of the attribute named \var{attr_name}, for object
- \var{o}, to the value \var{v}. Returns \code{-1} on failure. This
- is the equivalent of the Python statement
- \samp{\var{o}.\var{attr_name} = \var{v}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyObject_SetAttr}{PyObject *o,
- PyObject *attr_name, PyObject *v}
- Set the value of the attribute named \var{attr_name}, for object
- \var{o}, to the value \var{v}. Returns \code{-1} on failure. This
- is the equivalent of the Python statement
- \samp{\var{o}.\var{attr_name} = \var{v}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyObject_DelAttrString}{PyObject *o, char *attr_name}
- Delete attribute named \var{attr_name}, for object \var{o}. Returns
- \code{-1} on failure. This is the equivalent of the Python
- statement: \samp{del \var{o}.\var{attr_name}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyObject_DelAttr}{PyObject *o, PyObject *attr_name}
- Delete attribute named \var{attr_name}, for object \var{o}. Returns
- \code{-1} on failure. This is the equivalent of the Python
- statement \samp{del \var{o}.\var{attr_name}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyObject_RichCompare}{PyObject *o1,
- PyObject *o2, int opid}
- Compare the values of \var{o1} and \var{o2} using the operation
- specified by \var{opid}, which must be one of
- \constant{Py_LT},
- \constant{Py_LE},
- \constant{Py_EQ},
- \constant{Py_NE},
- \constant{Py_GT}, or
- \constant{Py_GE}, corresponding to
- \code{<},
- \code{<=},
- \code{==},
- \code{!=},
- \code{>}, or
- \code{>=} respectively. This is the equivalent of the Python expression
- \samp{\var{o1} op \var{o2}}, where \code{op} is the operator
- corresponding to \var{opid}. Returns the value of the comparison on
- success, or \NULL{} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyObject_RichCompareBool}{PyObject *o1,
- PyObject *o2, int opid}
- Compare the values of \var{o1} and \var{o2} using the operation
- specified by \var{opid}, which must be one of
- \constant{Py_LT},
- \constant{Py_LE},
- \constant{Py_EQ},
- \constant{Py_NE},
- \constant{Py_GT}, or
- \constant{Py_GE}, corresponding to
- \code{<},
- \code{<=},
- \code{==},
- \code{!=},
- \code{>}, or
- \code{>=} respectively. Returns \code{-1} on error, \code{0} if the
- result is false, \code{1} otherwise. This is the equivalent of the
- Python expression \samp{\var{o1} op \var{o2}}, where
- \code{op} is the operator corresponding to \var{opid}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyObject_Cmp}{PyObject *o1, PyObject *o2, int *result}
- Compare the values of \var{o1} and \var{o2} using a routine provided
- by \var{o1}, if one exists, otherwise with a routine provided by
- \var{o2}. The result of the comparison is returned in
- \var{result}. Returns \code{-1} on failure. This is the equivalent
- of the Python statement\bifuncindex{cmp} \samp{\var{result} =
- cmp(\var{o1}, \var{o2})}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyObject_Compare}{PyObject *o1, PyObject *o2}
- Compare the values of \var{o1} and \var{o2} using a routine provided
- by \var{o1}, if one exists, otherwise with a routine provided by
- \var{o2}. Returns the result of the comparison on success. On
- error, the value returned is undefined; use
- \cfunction{PyErr_Occurred()} to detect an error. This is equivalent
- to the Python expression\bifuncindex{cmp} \samp{cmp(\var{o1},
- \var{o2})}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyObject_Repr}{PyObject *o}
- Compute a string representation of object \var{o}. Returns the
- string representation on success, \NULL{} on failure. This is the
- equivalent of the Python expression \samp{repr(\var{o})}. Called by
- the \function{repr()}\bifuncindex{repr} built-in function and by
- reverse quotes.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyObject_Str}{PyObject *o}
- Compute a string representation of object \var{o}. Returns the
- string representation on success, \NULL{} on failure. This is the
- equivalent of the Python expression \samp{str(\var{o})}. Called by
- the \function{str()}\bifuncindex{str} built-in function and by the
- \keyword{print} statement.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyObject_Unicode}{PyObject *o}
- Compute a Unicode string representation of object \var{o}. Returns
- the Unicode string representation on success, \NULL{} on failure.
- This is the equivalent of the Python expression
- \samp{unicode(\var{o})}. Called by the
- \function{unicode()}\bifuncindex{unicode} built-in function.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyObject_IsInstance}{PyObject *inst, PyObject *cls}
- Returns \code{1} if \var{inst} is an instance of the class \var{cls}
- or a subclass of \var{cls}, or \code{0} if not. On error, returns
- \code{-1} and sets an exception. If \var{cls} is a type object
- rather than a class object, \cfunction{PyObject_IsInstance()}
- returns \code{1} if \var{inst} is of type \var{cls}. If \var{cls}
- is a tuple, the check will be done against every entry in \var{cls}.
- The result will be \code{1} when at least one of the checks returns
- \code{1}, otherwise it will be \code{0}. If \var{inst} is not a class
- instance and \var{cls} is neither a type object, nor a class object,
- nor a tuple, \var{inst} must have a \member{__class__} attribute
- --- the class relationship of the value of that attribute with
- \var{cls} will be used to determine the result of this function.
- \versionadded{2.1}
- \versionchanged[Support for a tuple as the second argument added]{2.2}
-\end{cfuncdesc}
-
-Subclass determination is done in a fairly straightforward way, but
-includes a wrinkle that implementors of extensions to the class system
-may want to be aware of. If \class{A} and \class{B} are class
-objects, \class{B} is a subclass of \class{A} if it inherits from
-\class{A} either directly or indirectly. If either is not a class
-object, a more general mechanism is used to determine the class
-relationship of the two objects. When testing if \var{B} is a
-subclass of \var{A}, if \var{A} is \var{B},
-\cfunction{PyObject_IsSubclass()} returns true. If \var{A} and
-\var{B} are different objects, \var{B}'s \member{__bases__} attribute
-is searched in a depth-first fashion for \var{A} --- the presence of
-the \member{__bases__} attribute is considered sufficient for this
-determination.
-
-\begin{cfuncdesc}{int}{PyObject_IsSubclass}{PyObject *derived,
- PyObject *cls}
- Returns \code{1} if the class \var{derived} is identical to or
- derived from the class \var{cls}, otherwise returns \code{0}. In
- case of an error, returns \code{-1}. If \var{cls}
- is a tuple, the check will be done against every entry in \var{cls}.
- The result will be \code{1} when at least one of the checks returns
- \code{1}, otherwise it will be \code{0}. If either \var{derived} or
- \var{cls} is not an actual class object (or tuple), this function
- uses the generic algorithm described above.
- \versionadded{2.1}
- \versionchanged[Older versions of Python did not support a tuple
- as the second argument]{2.3}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyCallable_Check}{PyObject *o}
- Determine if the object \var{o} is callable. Return \code{1} if the
- object is callable and \code{0} otherwise. This function always
- succeeds.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyObject_Call}{PyObject *callable_object,
- PyObject *args,
- PyObject *kw}
- Call a callable Python object \var{callable_object}, with arguments
- given by the tuple \var{args}, and named arguments given by the
- dictionary \var{kw}. If no named arguments are needed, \var{kw} may
- be \NULL{}. \var{args} must not be \NULL{}, use an empty tuple if
- no arguments are needed. Returns the result of the call on success,
- or \NULL{} on failure. This is the equivalent of the Python
- expression \samp{apply(\var{callable_object}, \var{args}, \var{kw})}
- or \samp{\var{callable_object}(*\var{args}, **\var{kw})}.
- \bifuncindex{apply}
- \versionadded{2.2}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyObject_CallObject}{PyObject *callable_object,
- PyObject *args}
- Call a callable Python object \var{callable_object}, with arguments
- given by the tuple \var{args}. If no arguments are needed, then
- \var{args} may be \NULL. Returns the result of the call on
- success, or \NULL{} on failure. This is the equivalent of the
- Python expression \samp{apply(\var{callable_object}, \var{args})} or
- \samp{\var{callable_object}(*\var{args})}.
- \bifuncindex{apply}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyObject_CallFunction}{PyObject *callable,
- char *format, \moreargs}
- Call a callable Python object \var{callable}, with a variable
- number of C arguments. The C arguments are described using a
- \cfunction{Py_BuildValue()} style format string. The format may be
- \NULL, indicating that no arguments are provided. Returns the
- result of the call on success, or \NULL{} on failure. This is the
- equivalent of the Python expression \samp{apply(\var{callable},
- \var{args})} or \samp{\var{callable}(*\var{args})}.
- \bifuncindex{apply}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyObject_CallMethod}{PyObject *o,
- char *method, char *format,
- \moreargs}
- Call the method named \var{m} of object \var{o} with a variable
- number of C arguments. The C arguments are described by a
- \cfunction{Py_BuildValue()} format string. The format may be \NULL,
- indicating that no arguments are provided. Returns the result of the
- call on success, or \NULL{} on failure. This is the equivalent of
- the Python expression \samp{\var{o}.\var{method}(\var{args})}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyObject_CallFunctionObjArgs}{PyObject *callable,
- \moreargs,
- \code{NULL}}
- Call a callable Python object \var{callable}, with a variable
- number of \ctype{PyObject*} arguments. The arguments are provided
- as a variable number of parameters followed by \NULL.
- Returns the result of the call on success, or \NULL{} on failure.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyObject_CallMethodObjArgs}{PyObject *o,
- PyObject *name,
- \moreargs,
- \code{NULL}}
- Calls a method of the object \var{o}, where the name of the method
- is given as a Python string object in \var{name}. It is called with
- a variable number of \ctype{PyObject*} arguments. The arguments are
- provided as a variable number of parameters followed by \NULL.
- Returns the result of the call on success, or \NULL{} on failure.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyObject_Hash}{PyObject *o}
- Compute and return the hash value of an object \var{o}. On failure,
- return \code{-1}. This is the equivalent of the Python expression
- \samp{hash(\var{o})}.\bifuncindex{hash}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyObject_IsTrue}{PyObject *o}
- Returns \code{1} if the object \var{o} is considered to be true, and
- \code{0} otherwise. This is equivalent to the Python expression
- \samp{not not \var{o}}. On failure, return \code{-1}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyObject_Not}{PyObject *o}
- Returns \code{0} if the object \var{o} is considered to be true, and
- \code{1} otherwise. This is equivalent to the Python expression
- \samp{not \var{o}}. On failure, return \code{-1}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyObject_Type}{PyObject *o}
- When \var{o} is non-\NULL, returns a type object corresponding to
- the object type of object \var{o}. On failure, raises
- \exception{SystemError} and returns \NULL. This is equivalent to
- the Python expression \code{type(\var{o})}.\bifuncindex{type}
- This function increments the reference count of the return value.
- There's really no reason to use this function instead of the
- common expression \code{\var{o}->ob_type}, which returns a pointer
- of type \ctype{PyTypeObject*}, except when the incremented reference
- count is needed.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyObject_TypeCheck}{PyObject *o, PyTypeObject *type}
- Return true if the object \var{o} is of type \var{type} or a subtype
- of \var{type}. Both parameters must be non-\NULL.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyObject_Length}{PyObject *o}
-\cfuncline{int}{PyObject_Size}{PyObject *o}
- Return the length of object \var{o}. If the object \var{o} provides
- both sequence and mapping protocols, the sequence length is
- returned. On error, \code{-1} is returned. This is the equivalent
- to the Python expression \samp{len(\var{o})}.\bifuncindex{len}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyObject_GetItem}{PyObject *o, PyObject *key}
- Return element of \var{o} corresponding to the object \var{key} or
- \NULL{} on failure. This is the equivalent of the Python expression
- \samp{\var{o}[\var{key}]}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyObject_SetItem}{PyObject *o,
- PyObject *key, PyObject *v}
- Map the object \var{key} to the value \var{v}. Returns \code{-1} on
- failure. This is the equivalent of the Python statement
- \samp{\var{o}[\var{key}] = \var{v}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyObject_DelItem}{PyObject *o, PyObject *key}
- Delete the mapping for \var{key} from \var{o}. Returns \code{-1} on
- failure. This is the equivalent of the Python statement \samp{del
- \var{o}[\var{key}]}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyObject_AsFileDescriptor}{PyObject *o}
- Derives a file-descriptor from a Python object. If the object is an
- integer or long integer, its value is returned. If not, the
- object's \method{fileno()} method is called if it exists; the method
- must return an integer or long integer, which is returned as the
- file descriptor value. Returns \code{-1} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyObject_Dir}{PyObject *o}
- This is equivalent to the Python expression \samp{dir(\var{o})},
- returning a (possibly empty) list of strings appropriate for the
- object argument, or \NULL{} if there was an error. If the argument
- is \NULL, this is like the Python \samp{dir()}, returning the names
- of the current locals; in this case, if no execution frame is active
- then \NULL{} is returned but \cfunction{PyErr_Occurred()} will
- return false.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyObject_GetIter}{PyObject *o}
- This is equivalent to the Python expression \samp{iter(\var{o})}.
- It returns a new iterator for the object argument, or the object
- itself if the object is already an iterator. Raises
- \exception{TypeError} and returns \NULL{} if the object cannot be
- iterated.
-\end{cfuncdesc}
-
-
-\section{Number Protocol \label{number}}
-
-\begin{cfuncdesc}{int}{PyNumber_Check}{PyObject *o}
- Returns \code{1} if the object \var{o} provides numeric protocols,
- and false otherwise. This function always succeeds.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Add}{PyObject *o1, PyObject *o2}
- Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
- failure. This is the equivalent of the Python expression
- \samp{\var{o1} + \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Subtract}{PyObject *o1, PyObject *o2}
- Returns the result of subtracting \var{o2} from \var{o1}, or \NULL{}
- on failure. This is the equivalent of the Python expression
- \samp{\var{o1} - \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Multiply}{PyObject *o1, PyObject *o2}
- Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{}
- on failure. This is the equivalent of the Python expression
- \samp{\var{o1} * \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Divide}{PyObject *o1, PyObject *o2}
- Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
- failure. This is the equivalent of the Python expression
- \samp{\var{o1} / \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_FloorDivide}{PyObject *o1, PyObject *o2}
- Return the floor of \var{o1} divided by \var{o2}, or \NULL{} on
- failure. This is equivalent to the ``classic'' division of
- integers.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_TrueDivide}{PyObject *o1, PyObject *o2}
- Return a reasonable approximation for the mathematical value of
- \var{o1} divided by \var{o2}, or \NULL{} on failure. The return
- value is ``approximate'' because binary floating point numbers are
- approximate; it is not possible to represent all real numbers in
- base two. This function can return a floating point value when
- passed two integers.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Remainder}{PyObject *o1, PyObject *o2}
- Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{}
- on failure. This is the equivalent of the Python expression
- \samp{\var{o1} \%\ \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Divmod}{PyObject *o1, PyObject *o2}
- See the built-in function \function{divmod()}\bifuncindex{divmod}.
- Returns \NULL{} on failure. This is the equivalent of the Python
- expression \samp{divmod(\var{o1}, \var{o2})}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Power}{PyObject *o1,
- PyObject *o2, PyObject *o3}
- See the built-in function \function{pow()}\bifuncindex{pow}.
- Returns \NULL{} on failure. This is the equivalent of the Python
- expression \samp{pow(\var{o1}, \var{o2}, \var{o3})}, where \var{o3}
- is optional. If \var{o3} is to be ignored, pass \cdata{Py_None} in
- its place (passing \NULL{} for \var{o3} would cause an illegal
- memory access).
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Negative}{PyObject *o}
- Returns the negation of \var{o} on success, or \NULL{} on failure.
- This is the equivalent of the Python expression \samp{-\var{o}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Positive}{PyObject *o}
- Returns \var{o} on success, or \NULL{} on failure. This is the
- equivalent of the Python expression \samp{+\var{o}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Absolute}{PyObject *o}
- Returns the absolute value of \var{o}, or \NULL{} on failure. This
- is the equivalent of the Python expression \samp{abs(\var{o})}.
- \bifuncindex{abs}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Invert}{PyObject *o}
- Returns the bitwise negation of \var{o} on success, or \NULL{} on
- failure. This is the equivalent of the Python expression
- \samp{\~\var{o}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Lshift}{PyObject *o1, PyObject *o2}
- Returns the result of left shifting \var{o1} by \var{o2} on success,
- or \NULL{} on failure. This is the equivalent of the Python
- expression \samp{\var{o1} <\code{<} \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Rshift}{PyObject *o1, PyObject *o2}
- Returns the result of right shifting \var{o1} by \var{o2} on
- success, or \NULL{} on failure. This is the equivalent of the
- Python expression \samp{\var{o1} >\code{>} \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_And}{PyObject *o1, PyObject *o2}
- Returns the ``bitwise and'' of \var{o2} and \var{o2} on success and
- \NULL{} on failure. This is the equivalent of the Python expression
- \samp{\var{o1} \&\ \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2}
- Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on
- success, or \NULL{} on failure. This is the equivalent of the
- Python expression \samp{\var{o1} \textasciicircum{} \var{o2}}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2}
- Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
- \NULL{} on failure. This is the equivalent of the Python expression
- \samp{\var{o1} | \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAdd}{PyObject *o1, PyObject *o2}
- Returns the result of adding \var{o1} and \var{o2}, or \NULL{} on
- failure. The operation is done \emph{in-place} when \var{o1}
- supports it. This is the equivalent of the Python statement
- \samp{\var{o1} += \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceSubtract}{PyObject *o1,
- PyObject *o2}
- Returns the result of subtracting \var{o2} from \var{o1}, or \NULL{}
- on failure. The operation is done \emph{in-place} when \var{o1}
- supports it. This is the equivalent of the Python statement
- \samp{\var{o1} -= \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceMultiply}{PyObject *o1,
- PyObject *o2}
- Returns the result of multiplying \var{o1} and \var{o2}, or \NULL{}
- on failure. The operation is done \emph{in-place} when \var{o1}
- supports it. This is the equivalent of the Python statement
- \samp{\var{o1} *= \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceDivide}{PyObject *o1,
- PyObject *o2}
- Returns the result of dividing \var{o1} by \var{o2}, or \NULL{} on
- failure. The operation is done \emph{in-place} when \var{o1}
- supports it. This is the equivalent of the Python statement
- \samp{\var{o1} /= \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceFloorDivide}{PyObject *o1,
- PyObject *o2}
- Returns the mathematical of dividing \var{o1} by \var{o2}, or
- \NULL{} on failure. The operation is done \emph{in-place} when
- \var{o1} supports it. This is the equivalent of the Python
- statement \samp{\var{o1} //= \var{o2}}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceTrueDivide}{PyObject *o1,
- PyObject *o2}
- Return a reasonable approximation for the mathematical value of
- \var{o1} divided by \var{o2}, or \NULL{} on failure. The return
- value is ``approximate'' because binary floating point numbers are
- approximate; it is not possible to represent all real numbers in
- base two. This function can return a floating point value when
- passed two integers. The operation is done \emph{in-place} when
- \var{o1} supports it.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRemainder}{PyObject *o1,
- PyObject *o2}
- Returns the remainder of dividing \var{o1} by \var{o2}, or \NULL{}
- on failure. The operation is done \emph{in-place} when \var{o1}
- supports it. This is the equivalent of the Python statement
- \samp{\var{o1} \%= \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlacePower}{PyObject *o1,
- PyObject *o2, PyObject *o3}
- See the built-in function \function{pow()}.\bifuncindex{pow}
- Returns \NULL{} on failure. The operation is done \emph{in-place}
- when \var{o1} supports it. This is the equivalent of the Python
- statement \samp{\var{o1} **= \var{o2}} when o3 is \cdata{Py_None},
- or an in-place variant of \samp{pow(\var{o1}, \var{o2}, \var{o3})}
- otherwise. If \var{o3} is to be ignored, pass \cdata{Py_None} in its
- place (passing \NULL{} for \var{o3} would cause an illegal memory
- access).
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceLshift}{PyObject *o1,
- PyObject *o2}
- Returns the result of left shifting \var{o1} by \var{o2} on success,
- or \NULL{} on failure. The operation is done \emph{in-place} when
- \var{o1} supports it. This is the equivalent of the Python
- statement \samp{\var{o1} <\code{<=} \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceRshift}{PyObject *o1,
- PyObject *o2}
- Returns the result of right shifting \var{o1} by \var{o2} on
- success, or \NULL{} on failure. The operation is done
- \emph{in-place} when \var{o1} supports it. This is the equivalent
- of the Python statement \samp{\var{o1} >\code{>=} \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceAnd}{PyObject *o1, PyObject *o2}
- Returns the ``bitwise and'' of \var{o1} and \var{o2} on success and
- \NULL{} on failure. The operation is done \emph{in-place} when
- \var{o1} supports it. This is the equivalent of the Python
- statement \samp{\var{o1} \&= \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceXor}{PyObject *o1, PyObject *o2}
- Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on
- success, or \NULL{} on failure. The operation is done
- \emph{in-place} when \var{o1} supports it. This is the equivalent
- of the Python statement \samp{\var{o1} \textasciicircum= \var{o2}}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceOr}{PyObject *o1, PyObject *o2}
- Returns the ``bitwise or'' of \var{o1} and \var{o2} on success, or
- \NULL{} on failure. The operation is done \emph{in-place} when
- \var{o1} supports it. This is the equivalent of the Python
- statement \samp{\var{o1} |= \var{o2}}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyNumber_Coerce}{PyObject **p1, PyObject **p2}
- This function takes the addresses of two variables of type
- \ctype{PyObject*}. If the objects pointed to by \code{*\var{p1}}
- and \code{*\var{p2}} have the same type, increment their reference
- count and return \code{0} (success). If the objects can be converted
- to a common numeric type, replace \code{*p1} and \code{*p2} by their
- converted value (with 'new' reference counts), and return \code{0}.
- If no conversion is possible, or if some other error occurs, return
- \code{-1} (failure) and don't increment the reference counts. The
- call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python
- statement \samp{\var{o1}, \var{o2} = coerce(\var{o1}, \var{o2})}.
- \bifuncindex{coerce}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o}
- Returns the \var{o} converted to an integer object on success, or
- \NULL{} on failure. If the argument is outside the integer range
- a long object will be returned instead. This is the equivalent
- of the Python expression \samp{int(\var{o})}.\bifuncindex{int}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Long}{PyObject *o}
- Returns the \var{o} converted to a long integer object on success,
- or \NULL{} on failure. This is the equivalent of the Python
- expression \samp{long(\var{o})}.\bifuncindex{long}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyNumber_Float}{PyObject *o}
- Returns the \var{o} converted to a float object on success, or
- \NULL{} on failure. This is the equivalent of the Python expression
- \samp{float(\var{o})}.\bifuncindex{float}
-\end{cfuncdesc}
-
-
-\section{Sequence Protocol \label{sequence}}
-
-\begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}
- Return \code{1} if the object provides sequence protocol, and
- \code{0} otherwise. This function always succeeds.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PySequence_Size}{PyObject *o}
- Returns the number of objects in sequence \var{o} on success, and
- \code{-1} on failure. For objects that do not provide sequence
- protocol, this is equivalent to the Python expression
- \samp{len(\var{o})}.\bifuncindex{len}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PySequence_Length}{PyObject *o}
- Alternate name for \cfunction{PySequence_Size()}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PySequence_Concat}{PyObject *o1, PyObject *o2}
- Return the concatenation of \var{o1} and \var{o2} on success, and
- \NULL{} on failure. This is the equivalent of the Python
- expression \samp{\var{o1} + \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PySequence_Repeat}{PyObject *o, int count}
- Return the result of repeating sequence object \var{o} \var{count}
- times, or \NULL{} on failure. This is the equivalent of the Python
- expression \samp{\var{o} * \var{count}}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceConcat}{PyObject *o1,
- PyObject *o2}
- Return the concatenation of \var{o1} and \var{o2} on success, and
- \NULL{} on failure. The operation is done \emph{in-place} when
- \var{o1} supports it. This is the equivalent of the Python
- expression \samp{\var{o1} += \var{o2}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PySequence_InPlaceRepeat}{PyObject *o, int count}
- Return the result of repeating sequence object \var{o} \var{count}
- times, or \NULL{} on failure. The operation is done \emph{in-place}
- when \var{o} supports it. This is the equivalent of the Python
- expression \samp{\var{o} *= \var{count}}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PySequence_GetItem}{PyObject *o, int i}
- Return the \var{i}th element of \var{o}, or \NULL{} on failure.
- This is the equivalent of the Python expression
- \samp{\var{o}[\var{i}]}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PySequence_GetSlice}{PyObject *o, int i1, int i2}
- Return the slice of sequence object \var{o} between \var{i1} and
- \var{i2}, or \NULL{} on failure. This is the equivalent of the
- Python expression \samp{\var{o}[\var{i1}:\var{i2}]}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PySequence_SetItem}{PyObject *o, int i, PyObject *v}
- Assign object \var{v} to the \var{i}th element of \var{o}. Returns
- \code{-1} on failure. This is the equivalent of the Python
- statement \samp{\var{o}[\var{i}] = \var{v}}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PySequence_DelItem}{PyObject *o, int i}
- Delete the \var{i}th element of object \var{o}. Returns \code{-1}
- on failure. This is the equivalent of the Python statement
- \samp{del \var{o}[\var{i}]}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PySequence_SetSlice}{PyObject *o, int i1,
- int i2, PyObject *v}
- Assign the sequence object \var{v} to the slice in sequence object
- \var{o} from \var{i1} to \var{i2}. This is the equivalent of the
- Python statement \samp{\var{o}[\var{i1}:\var{i2}] = \var{v}}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PySequence_DelSlice}{PyObject *o, int i1, int i2}
- Delete the slice in sequence object \var{o} from \var{i1} to
- \var{i2}. Returns \code{-1} on failure. This is the equivalent of
- the Python statement \samp{del \var{o}[\var{i1}:\var{i2}]}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
- Returns the \var{o} as a tuple on success, and \NULL{} on failure.
- This is equivalent to the Python expression \samp{tuple(\var{o})}.
- \bifuncindex{tuple}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PySequence_Count}{PyObject *o, PyObject *value}
- Return the number of occurrences of \var{value} in \var{o}, that is,
- return the number of keys for which \code{\var{o}[\var{key}] ==
- \var{value}}. On failure, return \code{-1}. This is equivalent to
- the Python expression \samp{\var{o}.count(\var{value})}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PySequence_Contains}{PyObject *o, PyObject *value}
- Determine if \var{o} contains \var{value}. If an item in \var{o} is
- equal to \var{value}, return \code{1}, otherwise return \code{0}.
- On error, return \code{-1}. This is equivalent to the Python
- expression \samp{\var{value} in \var{o}}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PySequence_Index}{PyObject *o, PyObject *value}
- Return the first index \var{i} for which \code{\var{o}[\var{i}] ==
- \var{value}}. On error, return \code{-1}. This is equivalent to
- the Python expression \samp{\var{o}.index(\var{value})}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PySequence_List}{PyObject *o}
- Return a list object with the same contents as the arbitrary
- sequence \var{o}. The returned list is guaranteed to be new.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PySequence_Tuple}{PyObject *o}
- Return a tuple object with the same contents as the arbitrary
- sequence \var{o}. If \var{o} is a tuple, a new reference will be
- returned, otherwise a tuple will be constructed with the appropriate
- contents.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PySequence_Fast}{PyObject *o, const char *m}
- Returns the sequence \var{o} as a tuple, unless it is already a
- tuple or list, in which case \var{o} is returned. Use
- \cfunction{PySequence_Fast_GET_ITEM()} to access the members of the
- result. Returns \NULL{} on failure. If the object is not a
- sequence, raises \exception{TypeError} with \var{m} as the message
- text.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PySequence_Fast_GET_ITEM}{PyObject *o, int i}
- Return the \var{i}th element of \var{o}, assuming that \var{o} was
- returned by \cfunction{PySequence_Fast()}, \var{o} is not \NULL,
- and that \var{i} is within bounds.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PySequence_ITEM}{PyObject *o, int i}
- Return the \var{i}th element of \var{o} or \NULL on failure.
- Macro form of \cfunction{PySequence_GetItem()} but without checking
- that \cfunction{PySequence_Check(\var{o})} is true and without
- adjustment for negative indices.
- \versionadded{2.3}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PySequence_Fast_GET_SIZE}{PyObject *o}
- Returns the length of \var{o}, assuming that \var{o} was
- returned by \cfunction{PySequence_Fast()} and that \var{o} is
- not \NULL. The size can also be gotten by calling
- \cfunction{PySequence_Size()} on \var{o}, but
- \cfunction{PySequence_Fast_GET_SIZE()} is faster because it can
- assume \var{o} is a list or tuple.
-\end{cfuncdesc}
-
-
-\section{Mapping Protocol \label{mapping}}
-
-\begin{cfuncdesc}{int}{PyMapping_Check}{PyObject *o}
- Return \code{1} if the object provides mapping protocol, and
- \code{0} otherwise. This function always succeeds.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyMapping_Length}{PyObject *o}
- Returns the number of keys in object \var{o} on success, and
- \code{-1} on failure. For objects that do not provide mapping
- protocol, this is equivalent to the Python expression
- \samp{len(\var{o})}.\bifuncindex{len}
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyMapping_DelItemString}{PyObject *o, char *key}
- Remove the mapping for object \var{key} from the object \var{o}.
- Return \code{-1} on failure. This is equivalent to the Python
- statement \samp{del \var{o}[\var{key}]}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyMapping_DelItem}{PyObject *o, PyObject *key}
- Remove the mapping for object \var{key} from the object \var{o}.
- Return \code{-1} on failure. This is equivalent to the Python
- statement \samp{del \var{o}[\var{key}]}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyMapping_HasKeyString}{PyObject *o, char *key}
- On success, return \code{1} if the mapping object has the key
- \var{key} and \code{0} otherwise. This is equivalent to the Python
- expression \samp{\var{o}.has_key(\var{key})}. This function always
- succeeds.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{int}{PyMapping_HasKey}{PyObject *o, PyObject *key}
- Return \code{1} if the mapping object has the key \var{key} and
- \code{0} otherwise. This is equivalent to the Python expression
- \samp{\var{o}.has_key(\var{key})}. This function always succeeds.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyMapping_Keys}{PyObject *o}
- On success, return a list of the keys in object \var{o}. On
- failure, return \NULL. This is equivalent to the Python expression
- \samp{\var{o}.keys()}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyMapping_Values}{PyObject *o}
- On success, return a list of the values in object \var{o}. On
- failure, return \NULL. This is equivalent to the Python expression
- \samp{\var{o}.values()}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyMapping_Items}{PyObject *o}
- On success, return a list of the items in object \var{o}, where each
- item is a tuple containing a key-value pair. On failure, return
- \NULL. This is equivalent to the Python expression
- \samp{\var{o}.items()}.
-\end{cfuncdesc}
-
-
-\begin{cfuncdesc}{PyObject*}{PyMapping_GetItemString}{PyObject *o, char *key}
- Return element of \var{o} corresponding to the object \var{key} or
- \NULL{} on failure. This is the equivalent of the Python expression
- \samp{\var{o}[\var{key}]}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyMapping_SetItemString}{PyObject *o, char *key,
- PyObject *v}
- Map the object \var{key} to the value \var{v} in object \var{o}.
- Returns \code{-1} on failure. This is the equivalent of the Python
- statement \samp{\var{o}[\var{key}] = \var{v}}.
-\end{cfuncdesc}
-
-
-\section{Iterator Protocol \label{iterator}}
-
-\versionadded{2.2}
-
-There are only a couple of functions specifically for working with
-iterators.
-
-\begin{cfuncdesc}{int}{PyIter_Check}{PyObject *o}
- Return true if the object \var{o} supports the iterator protocol.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyIter_Next}{PyObject *o}
- Return the next value from the iteration \var{o}. If the object is
- an iterator, this retrieves the next value from the iteration, and
- returns \NULL{} with no exception set if there are no remaining
- items. If the object is not an iterator, \exception{TypeError} is
- raised, or if there is an error in retrieving the item, returns
- \NULL{} and passes along the exception.
-\end{cfuncdesc}
-
-To write a loop which iterates over an iterator, the C code should
-look something like this:
-
-\begin{verbatim}
-PyObject *iterator = PyObject_GetIter(obj);
-PyObject *item;
-
-if (iterator == NULL) {
- /* propagate error */
-}
-
-while (item = PyIter_Next(iterator)) {
- /* do something with item */
- ...
- /* release reference when done */
- Py_DECREF(item);
-}
-
-Py_DECREF(iterator);
-
-if (PyErr_Occurred()) {
- /* propagate error */
-}
-else {
- /* continue doing useful work */
-}
-\end{verbatim}
-
-
-\section{Buffer Protocol \label{abstract-buffer}}
-
-\begin{cfuncdesc}{int}{PyObject_AsCharBuffer}{PyObject *obj,
- const char **buffer,
- int *buffer_len}
- Returns a pointer to a read-only memory location useable as character-
- based input. The \var{obj} argument must support the single-segment
- character buffer interface. On success, returns \code{0}, sets
- \var{buffer} to the memory location and \var{buffer_len} to the buffer
- length. Returns \code{-1} and sets a \exception{TypeError} on error.
- \versionadded{1.6}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyObject_AsReadBuffer}{PyObject *obj,
- const char **buffer,
- int *buffer_len}
- Returns a pointer to a read-only memory location containing
- arbitrary data. The \var{obj} argument must support the
- single-segment readable buffer interface. On success, returns
- \code{0}, sets \var{buffer} to the memory location and \var{buffer_len}
- to the buffer length. Returns \code{-1} and sets a
- \exception{TypeError} on error.
- \versionadded{1.6}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyObject_CheckReadBuffer}{PyObject *o}
- Returns \code{1} if \var{o} supports the single-segment readable
- buffer interface. Otherwise returns \code{0}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyObject_AsWriteBuffer}{PyObject *obj,
- char **buffer,
- int *buffer_len}
- Returns a pointer to a writeable memory location. The \var{obj}
- argument must support the single-segment, character buffer
- interface. On success, returns \code{0}, sets \var{buffer} to the
- memory location and \var{buffer_len} to the buffer length. Returns
- \code{-1} and sets a \exception{TypeError} on error.
- \versionadded{1.6}
-\end{cfuncdesc}
diff --git a/Doc/api/api.tex b/Doc/api/api.tex
deleted file mode 100644
index 6fa8c4177d..0000000000
--- a/Doc/api/api.tex
+++ /dev/null
@@ -1,65 +0,0 @@
-\documentclass{manual}
-
-\title{Python/C API Reference Manual}
-
-\input{boilerplate}
-
-\makeindex % tell \index to actually write the .idx file
-
-
-\begin{document}
-
-\maketitle
-
-\ifhtml
-\chapter*{Front Matter\label{front}}
-\fi
-
-\input{copyright}
-
-\begin{abstract}
-
-\noindent
-This manual documents the API used by C and \Cpp{} programmers who
-want to write extension modules or embed Python. It is a companion to
-\citetitle[../ext/ext.html]{Extending and Embedding the Python
-Interpreter}, which describes the general principles of extension
-writing but does not document the API functions in detail.
-
-\warning{The current version of this document is incomplete. I hope
-that it is nevertheless useful. I will continue to work on it, and
-release new versions from time to time, independent from Python source
-code releases.}
-
-\end{abstract}
-
-\tableofcontents
-
-
-\input{intro}
-\input{veryhigh}
-\input{refcounting}
-\input{exceptions}
-\input{utilities}
-\input{abstract}
-\input{concrete}
-\input{init}
-\input{memory}
-\input{newtypes}
-
-
-% \chapter{Debugging \label{debugging}}
-%
-% XXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.
-
-
-\appendix
-\chapter{Reporting Bugs}
-\input{reportingbugs}
-
-\chapter{History and License}
-\input{license}
-
-\input{api.ind} % Index -- must be last
-
-\end{document}
diff --git a/Doc/api/concrete.tex b/Doc/api/concrete.tex
deleted file mode 100644
index 2c14596f56..0000000000
--- a/Doc/api/concrete.tex
+++ /dev/null
@@ -1,2554 +0,0 @@
-\chapter{Concrete Objects Layer \label{concrete}}
-
-
-The functions in this chapter are specific to certain Python object
-types. Passing them an object of the wrong type is not a good idea;
-if you receive an object from a Python program and you are not sure
-that it has the right type, you must perform a type check first;
-for example, to check that an object is a dictionary, use
-\cfunction{PyDict_Check()}. The chapter is structured like the
-``family tree'' of Python object types.
-
-\warning{While the functions described in this chapter carefully check
-the type of the objects which are passed in, many of them do not check
-for \NULL{} being passed instead of a valid object. Allowing \NULL{}
-to be passed in can cause memory access violations and immediate
-termination of the interpreter.}
-
-
-\section{Fundamental Objects \label{fundamental}}
-
-This section describes Python type objects and the singleton object
-\code{None}.
-
-
-\subsection{Type Objects \label{typeObjects}}
-
-\obindex{type}
-\begin{ctypedesc}{PyTypeObject}
- The C structure of the objects used to describe built-in types.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyObject*}{PyType_Type}
- This is the type object for type objects; it is the same object as
- \code{types.TypeType} in the Python layer.
- \withsubitem{(in module types)}{\ttindex{TypeType}}
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyType_Check}{PyObject *o}
- Returns true if the object \var{o} is a type object, including
- instances of types derived from the standard type object. Returns
- false in all other cases.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyType_CheckExact}{PyObject *o}
- Returns true if the object \var{o} is a type object, but not a
- subtype of the standard type object. Returns false in all other
- cases.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyType_HasFeature}{PyObject *o, int feature}
- Returns true if the type object \var{o} sets the feature
- \var{feature}. Type features are denoted by single bit flags.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyType_IS_GC}{PyObject *o}
- Return true if the type object includes support for the cycle
- detector; this tests the type flag \constant{Py_TPFLAGS_HAVE_GC}.
- \versionadded{2.0}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyType_IsSubtype}{PyTypeObject *a, PyTypeObject *b}
- Returns true if \var{a} is a subtype of \var{b}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyType_GenericAlloc}{PyTypeObject *type,
- int nitems}
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyType_GenericNew}{PyTypeObject *type,
- PyObject *args, PyObject *kwds}
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyType_Ready}{PyTypeObject *type}
- Finalize a type object. This should be called on all type objects
- to finish their initialization. This function is responsible for
- adding inherited slots from a type's base class. Returns \code{0}
- on success, or returns \code{-1} and sets an exception on error.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-
-\subsection{The None Object \label{noneObject}}
-
-\obindex{None@\texttt{None}}
-Note that the \ctype{PyTypeObject} for \code{None} is not directly
-exposed in the Python/C API. Since \code{None} is a singleton,
-testing for object identity (using \samp{==} in C) is sufficient.
-There is no \cfunction{PyNone_Check()} function for the same reason.
-
-\begin{cvardesc}{PyObject*}{Py_None}
- The Python \code{None} object, denoting lack of value. This object
- has no methods. It needs to be treated just like any other object
- with respect to reference counts.
-\end{cvardesc}
-
-
-\section{Numeric Objects \label{numericObjects}}
-
-\obindex{numeric}
-
-
-\subsection{Plain Integer Objects \label{intObjects}}
-
-\obindex{integer}
-\begin{ctypedesc}{PyIntObject}
- This subtype of \ctype{PyObject} represents a Python integer
- object.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyTypeObject}{PyInt_Type}
- This instance of \ctype{PyTypeObject} represents the Python plain
- integer type. This is the same object as \code{types.IntType}.
- \withsubitem{(in modules types)}{\ttindex{IntType}}
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o}
- Returns true if \var{o} is of type \cdata{PyInt_Type} or a subtype
- of \cdata{PyInt_Type}.
- \versionchanged[Allowed subtypes to be accepted]{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyInt_CheckExact}{PyObject* o}
- Returns true if \var{o} is of type \cdata{PyInt_Type}, but not a
- subtype of \cdata{PyInt_Type}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyInt_FromString}{char *str, char **pend,
- int base}
- Return a new \ctype{PyIntObject} or \ctype{PyLongObject} based on the
- string value in \var{str}, which is interpreted according to the radix in
- \var{base}. If \var{pend} is non-\NULL, \code{*\var{pend}} will point to
- the first character in \var{str} which follows the representation of the
- number. If \var{base} is \code{0}, the radix will be determined based on
- the leading characters of \var{str}: if \var{str} starts with \code{'0x'}
- or \code{'0X'}, radix 16 will be used; if \var{str} starts with
- \code{'0'}, radix 8 will be used; otherwise radix 10 will be used. If
- \var{base} is not \code{0}, it must be between \code{2} and \code{36},
- inclusive. Leading spaces are ignored. If there are no digits,
- \exception{ValueError} will be raised. If the string represents a number
- too large to be contained within the machine's \ctype{long int} type and
- overflow warnings are being suppressed, a \ctype{PyLongObject} will be
- returned. If overflow warnings are not being suppressed, \NULL{} will be
- returned in this case.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival}
- Creates a new integer object with a value of \var{ival}.
-
- The current implementation keeps an array of integer objects for all
- integers between \code{-1} and \code{100}, when you create an int in
- that range you actually just get back a reference to the existing
- object. So it should be possible to change the value of \code{1}. I
- suspect the behaviour of Python in this case is undefined. :-)
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io}
- Will first attempt to cast the object to a \ctype{PyIntObject}, if
- it is not already one, and then return its value.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io}
- Returns the value of the object \var{io}. No error checking is
- performed.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{unsigned long}{PyInt_AsUnsignedLongMask}{PyObject *io}
- Will first attempt to cast the object to a \ctype{PyIntObject} or
- \ctype{PyLongObject}, if it is not already one, and then return its
- value as unsigned long. This function does not check for overflow.
- \versionadded{2.3}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{unsigned long}{PyInt_AsUnsignedLongLongMask}{PyObject *io}
- Will first attempt to cast the object to a \ctype{PyIntObject} or
- \ctype{PyLongObject}, if it is not already one, and then return its
- value as unsigned long long, without checking for overflow.
- \versionadded{2.3}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{long}{PyInt_GetMax}{}
- Returns the system's idea of the largest integer it can handle
- (\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system
- header files).
-\end{cfuncdesc}
-
-
-\subsection{Long Integer Objects \label{longObjects}}
-
-\obindex{long integer}
-\begin{ctypedesc}{PyLongObject}
- This subtype of \ctype{PyObject} represents a Python long integer
- object.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyTypeObject}{PyLong_Type}
- This instance of \ctype{PyTypeObject} represents the Python long
- integer type. This is the same object as \code{types.LongType}.
- \withsubitem{(in modules types)}{\ttindex{LongType}}
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p}
- Returns true if its argument is a \ctype{PyLongObject} or a subtype
- of \ctype{PyLongObject}.
- \versionchanged[Allowed subtypes to be accepted]{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyLong_CheckExact}{PyObject *p}
- Returns true if its argument is a \ctype{PyLongObject}, but not a
- subtype of \ctype{PyLongObject}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v}
- Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{}
- on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v}
- Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
- long}, or \NULL{} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyLong_FromLongLong}{long long v}
- Returns a new \ctype{PyLongObject} object from a C \ctype{long long},
- or \NULL{} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLongLong}{unsigned long long v}
- Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned
- long long}, or \NULL{} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v}
- Returns a new \ctype{PyLongObject} object from the integer part of
- \var{v}, or \NULL{} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend,
- int base}
- Return a new \ctype{PyLongObject} based on the string value in
- \var{str}, which is interpreted according to the radix in
- \var{base}. If \var{pend} is non-\NULL, \code{*\var{pend}} will
- point to the first character in \var{str} which follows the
- representation of the number. If \var{base} is \code{0}, the radix
- will be determined based on the leading characters of \var{str}: if
- \var{str} starts with \code{'0x'} or \code{'0X'}, radix 16 will be
- used; if \var{str} starts with \code{'0'}, radix 8 will be used;
- otherwise radix 10 will be used. If \var{base} is not \code{0}, it
- must be between \code{2} and \code{36}, inclusive. Leading spaces
- are ignored. If there are no digits, \exception{ValueError} will be
- raised.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyLong_FromUnicode}{Py_UNICODE *u,
- int length, int base}
- Convert a sequence of Unicode digits to a Python long integer
- value. The first parameter, \var{u}, points to the first character
- of the Unicode string, \var{length} gives the number of characters,
- and \var{base} is the radix for the conversion. The radix must be
- in the range [2, 36]; if it is out of range, \exception{ValueError}
- will be raised.
- \versionadded{1.6}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyLong_FromVoidPtr}{void *p}
- Create a Python integer or long integer from the pointer \var{p}.
- The pointer value can be retrieved from the resulting value using
- \cfunction{PyLong_AsVoidPtr()}.
- \versionadded{1.5.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong}
- Returns a C \ctype{long} representation of the contents of
- \var{pylong}. If \var{pylong} is greater than
- \constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError}
- is raised.
- \withsubitem{(built-in exception)}{\ttindex{OverflowError}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong}
- Returns a C \ctype{unsigned long} representation of the contents of
- \var{pylong}. If \var{pylong} is greater than
- \constant{ULONG_MAX}\ttindex{ULONG_MAX}, an
- \exception{OverflowError} is raised.
- \withsubitem{(built-in exception)}{\ttindex{OverflowError}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{long long}{PyLong_AsLongLong}{PyObject *pylong}
- Return a C \ctype{long long} from a Python long integer. If
- \var{pylong} cannot be represented as a \ctype{long long}, an
- \exception{OverflowError} will be raised.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{unsigned long long}{PyLong_AsUnsignedLongLong}{PyObject
- *pylong}
- Return a C \ctype{unsigned long long} from a Python long integer.
- If \var{pylong} cannot be represented as an \ctype{unsigned long
- long}, an \exception{OverflowError} will be raised if the value is
- positive, or a \exception{TypeError} will be raised if the value is
- negative.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLongMask}{PyObject *io}
- Return a C \ctype{unsigned long} from a Python long integer, without
- checking for overflow.
- \versionadded{2.3}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLongLongMask}{PyObject *io}
- Return a C \ctype{unsigned long long} from a Python long integer, without
- checking for overflow.
- \versionadded{2.3}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong}
- Returns a C \ctype{double} representation of the contents of
- \var{pylong}. If \var{pylong} cannot be approximately represented
- as a \ctype{double}, an \exception{OverflowError} exception is
- raised and \code{-1.0} will be returned.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void*}{PyLong_AsVoidPtr}{PyObject *pylong}
- Convert a Python integer or long integer \var{pylong} to a C
- \ctype{void} pointer. If \var{pylong} cannot be converted, an
- \exception{OverflowError} will be raised. This is only assured to
- produce a usable \ctype{void} pointer for values created with
- \cfunction{PyLong_FromVoidPtr()}.
- \versionadded{1.5.2}
-\end{cfuncdesc}
-
-
-\subsection{Floating Point Objects \label{floatObjects}}
-
-\obindex{floating point}
-\begin{ctypedesc}{PyFloatObject}
- This subtype of \ctype{PyObject} represents a Python floating point
- object.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyTypeObject}{PyFloat_Type}
- This instance of \ctype{PyTypeObject} represents the Python floating
- point type. This is the same object as \code{types.FloatType}.
- \withsubitem{(in modules types)}{\ttindex{FloatType}}
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p}
- Returns true if its argument is a \ctype{PyFloatObject} or a subtype
- of \ctype{PyFloatObject}.
- \versionchanged[Allowed subtypes to be accepted]{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyFloat_CheckExact}{PyObject *p}
- Returns true if its argument is a \ctype{PyFloatObject}, but not a
- subtype of \ctype{PyFloatObject}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyFloat_FromString}{PyObject *str, char **pend}
- Creates a \ctype{PyFloatObject} object based on the string value in
- \var{str}, or \NULL{} on failure. The \var{pend} argument is ignored. It
- remains only for backward compatibility.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v}
- Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on
- failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat}
- Returns a C \ctype{double} representation of the contents of
- \var{pyfloat}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat}
- Returns a C \ctype{double} representation of the contents of
- \var{pyfloat}, but without error checking.
-\end{cfuncdesc}
-
-
-\subsection{Complex Number Objects \label{complexObjects}}
-
-\obindex{complex number}
-Python's complex number objects are implemented as two distinct types
-when viewed from the C API: one is the Python object exposed to
-Python programs, and the other is a C structure which represents the
-actual complex number value. The API provides functions for working
-with both.
-
-\subsubsection{Complex Numbers as C Structures}
-
-Note that the functions which accept these structures as parameters
-and return them as results do so \emph{by value} rather than
-dereferencing them through pointers. This is consistent throughout
-the API.
-
-\begin{ctypedesc}{Py_complex}
- The C structure which corresponds to the value portion of a Python
- complex number object. Most of the functions for dealing with
- complex number objects use structures of this type as input or
- output values, as appropriate. It is defined as:
-
-\begin{verbatim}
-typedef struct {
- double real;
- double imag;
-} Py_complex;
-\end{verbatim}
-\end{ctypedesc}
-
-\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right}
- Return the sum of two complex numbers, using the C
- \ctype{Py_complex} representation.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right}
- Return the difference between two complex numbers, using the C
- \ctype{Py_complex} representation.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex}
- Return the negation of the complex number \var{complex}, using the C
- \ctype{Py_complex} representation.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right}
- Return the product of two complex numbers, using the C
- \ctype{Py_complex} representation.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend,
- Py_complex divisor}
- Return the quotient of two complex numbers, using the C
- \ctype{Py_complex} representation.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp}
- Return the exponentiation of \var{num} by \var{exp}, using the C
- \ctype{Py_complex} representation.
-\end{cfuncdesc}
-
-
-\subsubsection{Complex Numbers as Python Objects}
-
-\begin{ctypedesc}{PyComplexObject}
- This subtype of \ctype{PyObject} represents a Python complex number
- object.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyTypeObject}{PyComplex_Type}
- This instance of \ctype{PyTypeObject} represents the Python complex
- number type.
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
- Returns true if its argument is a \ctype{PyComplexObject} or a
- subtype of \ctype{PyComplexObject}.
- \versionchanged[Allowed subtypes to be accepted]{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyComplex_CheckExact}{PyObject *p}
- Returns true if its argument is a \ctype{PyComplexObject}, but not a
- subtype of \ctype{PyComplexObject}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v}
- Create a new Python complex number object from a C
- \ctype{Py_complex} value.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag}
- Returns a new \ctype{PyComplexObject} object from \var{real} and
- \var{imag}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op}
- Returns the real part of \var{op} as a C \ctype{double}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op}
- Returns the imaginary part of \var{op} as a C \ctype{double}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op}
- Returns the \ctype{Py_complex} value of the complex number
- \var{op}.
-\end{cfuncdesc}
-
-
-
-\section{Sequence Objects \label{sequenceObjects}}
-
-\obindex{sequence}
-Generic operations on sequence objects were discussed in the previous
-chapter; this section deals with the specific kinds of sequence
-objects that are intrinsic to the Python language.
-
-
-\subsection{String Objects \label{stringObjects}}
-
-These functions raise \exception{TypeError} when expecting a string
-parameter and are called with a non-string parameter.
-
-\obindex{string}
-\begin{ctypedesc}{PyStringObject}
- This subtype of \ctype{PyObject} represents a Python string object.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyTypeObject}{PyString_Type}
- This instance of \ctype{PyTypeObject} represents the Python string
- type; it is the same object as \code{types.TypeType} in the Python
- layer.
- \withsubitem{(in module types)}{\ttindex{StringType}}.
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyString_Check}{PyObject *o}
- Returns true if the object \var{o} is a string object or an instance
- of a subtype of the string type.
- \versionchanged[Allowed subtypes to be accepted]{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyString_CheckExact}{PyObject *o}
- Returns true if the object \var{o} is a string object, but not an
- instance of a subtype of the string type.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v}
- Returns a new string object with the value \var{v} on success, and
- \NULL{} on failure. The parameter \var{v} must not be \NULL; it
- will not be checked.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v,
- int len}
- Returns a new string object with the value \var{v} and length
- \var{len} on success, and \NULL{} on failure. If \var{v} is
- \NULL, the contents of the string are uninitialized.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyString_FromFormat}{const char *format, ...}
- Takes a C \cfunction{printf()}-style \var{format} string and a
- variable number of arguments, calculates the size of the resulting
- Python string and returns a string with the values formatted into
- it. The variable arguments must be C types and must correspond
- exactly to the format characters in the \var{format} string. The
- following format characters are allowed:
-
- \begin{tableiii}{l|l|l}{member}{Format Characters}{Type}{Comment}
- \lineiii{\%\%}{\emph{n/a}}{The literal \% character.}
- \lineiii{\%c}{int}{A single character, represented as an C int.}
- \lineiii{\%d}{int}{Exactly equivalent to \code{printf("\%d")}.}
- \lineiii{\%ld}{long}{Exactly equivalent to \code{printf("\%ld")}.}
- \lineiii{\%i}{int}{Exactly equivalent to \code{printf("\%i")}.}
- \lineiii{\%x}{int}{Exactly equivalent to \code{printf("\%x")}.}
- \lineiii{\%s}{char*}{A null-terminated C character array.}
- \lineiii{\%p}{void*}{The hex representation of a C pointer.
- Mostly equivalent to \code{printf("\%p")} except that it is
- guaranteed to start with the literal \code{0x} regardless of
- what the platform's \code{printf} yields.}
- \end{tableiii}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyString_FromFormatV}{const char *format,
- va_list vargs}
- Identical to \function{PyString_FromFormat()} except that it takes
- exactly two arguments.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyString_Size}{PyObject *string}
- Returns the length of the string in string object \var{string}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyString_GET_SIZE}{PyObject *string}
- Macro form of \cfunction{PyString_Size()} but without error
- checking.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{char*}{PyString_AsString}{PyObject *string}
- Returns a NUL-terminated representation of the contents of
- \var{string}. The pointer refers to the internal buffer of
- \var{string}, not a copy. The data must not be modified in any way,
- unless the string was just created using
- \code{PyString_FromStringAndSize(NULL, \var{size})}.
- It must not be deallocated. If \var{string} is a Unicode object,
- this function computes the default encoding of \var{string} and
- operates on that. If \var{string} is not a string object at all,
- \cfunction{PyString_AsString()} returns \NULL{} and raises
- \exception{TypeError}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{char*}{PyString_AS_STRING}{PyObject *string}
- Macro form of \cfunction{PyString_AsString()} but without error
- checking. Only string objects are supported; no Unicode objects
- should be passed.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyString_AsStringAndSize}{PyObject *obj,
- char **buffer,
- int *length}
- Returns a NUL-terminated representation of the contents of the
- object \var{obj} through the output variables \var{buffer} and
- \var{length}.
-
- The function accepts both string and Unicode objects as input. For
- Unicode objects it returns the default encoded version of the
- object. If \var{length} is \NULL, the resulting buffer may not
- contain NUL characters; if it does, the function returns \code{-1}
- and a \exception{TypeError} is raised.
-
- The buffer refers to an internal string buffer of \var{obj}, not a
- copy. The data must not be modified in any way, unless the string
- was just created using \code{PyString_FromStringAndSize(NULL,
- \var{size})}. It must not be deallocated. If \var{string} is a
- Unicode object, this function computes the default encoding of
- \var{string} and operates on that. If \var{string} is not a string
- object at all, \cfunction{PyString_AsString()} returns \NULL{} and
- raises \exception{TypeError}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyString_Concat}{PyObject **string,
- PyObject *newpart}
- Creates a new string object in \var{*string} containing the contents
- of \var{newpart} appended to \var{string}; the caller will own the
- new reference. The reference to the old value of \var{string} will
- be stolen. If the new string cannot be created, the old reference
- to \var{string} will still be discarded and the value of
- \var{*string} will be set to \NULL; the appropriate exception will
- be set.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyString_ConcatAndDel}{PyObject **string,
- PyObject *newpart}
- Creates a new string object in \var{*string} containing the contents
- of \var{newpart} appended to \var{string}. This version decrements
- the reference count of \var{newpart}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{_PyString_Resize}{PyObject **string, int newsize}
- A way to resize a string object even though it is ``immutable''.
- Only use this to build up a brand new string object; don't use this
- if the string may already be known in other parts of the code. It
- is an error to call this function if the refcount on the input string
- object is not one.
- Pass the address of an existing string object as an lvalue (it may
- be written into), and the new size desired. On success, \var{*string}
- holds the resized string object and \code{0} is returned; the address in
- \var{*string} may differ from its input value. If the
- reallocation fails, the original string object at \var{*string} is
- deallocated, \var{*string} is set to \NULL{}, a memory exception is set,
- and \code{-1} is returned.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyString_Format}{PyObject *format,
- PyObject *args}
- Returns a new string object from \var{format} and \var{args}.
- Analogous to \code{\var{format} \%\ \var{args}}. The \var{args}
- argument must be a tuple.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyString_InternInPlace}{PyObject **string}
- Intern the argument \var{*string} in place. The argument must be
- the address of a pointer variable pointing to a Python string
- object. If there is an existing interned string that is the same as
- \var{*string}, it sets \var{*string} to it (decrementing the
- reference count of the old string object and incrementing the
- reference count of the interned string object), otherwise it leaves
- \var{*string} alone and interns it (incrementing its reference
- count). (Clarification: even though there is a lot of talk about
- reference counts, think of this function as reference-count-neutral;
- you own the object after the call if and only if you owned it before
- the call.)
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyString_InternFromString}{const char *v}
- A combination of \cfunction{PyString_FromString()} and
- \cfunction{PyString_InternInPlace()}, returning either a new string
- object that has been interned, or a new (``owned'') reference to an
- earlier interned string object with the same value.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyString_Decode}{const char *s,
- int size,
- const char *encoding,
- const char *errors}
- Creates an object by decoding \var{size} bytes of the encoded
- buffer \var{s} using the codec registered for
- \var{encoding}. \var{encoding} and \var{errors} have the same
- meaning as the parameters of the same name in the
- \function{unicode()} built-in function. The codec to be used is
- looked up using the Python codec registry. Returns \NULL{} if
- an exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyString_AsDecodedObject}{PyObject *str,
- const char *encoding,
- const char *errors}
- Decodes a string object by passing it to the codec registered for
- \var{encoding} and returns the result as Python
- object. \var{encoding} and \var{errors} have the same meaning as the
- parameters of the same name in the string \method{encode()} method.
- The codec to be used is looked up using the Python codec registry.
- Returns \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyString_Encode}{const char *s,
- int size,
- const char *encoding,
- const char *errors}
- Encodes the \ctype{char} buffer of the given size by passing it to
- the codec registered for \var{encoding} and returns a Python object.
- \var{encoding} and \var{errors} have the same meaning as the
- parameters of the same name in the string \method{encode()} method.
- The codec to be used is looked up using the Python codec
- registry. Returns \NULL{} if an exception was raised by the
- codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyString_AsEncodedObject}{PyObject *str,
- const char *encoding,
- const char *errors}
- Encodes a string object using the codec registered for
- \var{encoding} and returns the result as Python object.
- \var{encoding} and \var{errors} have the same meaning as the
- parameters of the same name in the string \method{encode()} method.
- The codec to be used is looked up using the Python codec registry.
- Returns \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-
-\subsection{Unicode Objects \label{unicodeObjects}}
-\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
-
-%--- Unicode Type -------------------------------------------------------
-
-These are the basic Unicode object types used for the Unicode
-implementation in Python:
-
-\begin{ctypedesc}{Py_UNICODE}
- This type represents a 16-bit unsigned storage type which is used by
- Python internally as basis for holding Unicode ordinals. On
- platforms where \ctype{wchar_t} is available and also has 16-bits,
- \ctype{Py_UNICODE} is a typedef alias for \ctype{wchar_t} to enhance
- native platform compatibility. On all other platforms,
- \ctype{Py_UNICODE} is a typedef alias for \ctype{unsigned short}.
-\end{ctypedesc}
-
-\begin{ctypedesc}{PyUnicodeObject}
- This subtype of \ctype{PyObject} represents a Python Unicode object.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
- This instance of \ctype{PyTypeObject} represents the Python Unicode
- type.
-\end{cvardesc}
-
-The following APIs are really C macros and can be used to do fast
-checks and to access internal read-only data of Unicode objects:
-
-\begin{cfuncdesc}{int}{PyUnicode_Check}{PyObject *o}
- Returns true if the object \var{o} is a Unicode object or an
- instance of a Unicode subtype.
- \versionchanged[Allowed subtypes to be accepted]{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyUnicode_CheckExact}{PyObject *o}
- Returns true if the object \var{o} is a Unicode object, but not an
- instance of a subtype.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyUnicode_GET_SIZE}{PyObject *o}
- Returns the size of the object. \var{o} has to be a
- \ctype{PyUnicodeObject} (not checked).
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyUnicode_GET_DATA_SIZE}{PyObject *o}
- Returns the size of the object's internal buffer in bytes. \var{o}
- has to be a \ctype{PyUnicodeObject} (not checked).
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AS_UNICODE}{PyObject *o}
- Returns a pointer to the internal \ctype{Py_UNICODE} buffer of the
- object. \var{o} has to be a \ctype{PyUnicodeObject} (not checked).
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{const char*}{PyUnicode_AS_DATA}{PyObject *o}
- Returns a pointer to the internal buffer of the object.
- \var{o} has to be a \ctype{PyUnicodeObject} (not checked).
-\end{cfuncdesc}
-
-% --- Unicode character properties ---------------------------------------
-
-Unicode provides many different character properties. The most often
-needed ones are available through these macros which are mapped to C
-functions depending on the Python configuration.
-
-\begin{cfuncdesc}{int}{Py_UNICODE_ISSPACE}{Py_UNICODE ch}
- Returns 1/0 depending on whether \var{ch} is a whitespace
- character.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_UNICODE_ISLOWER}{Py_UNICODE ch}
- Returns 1/0 depending on whether \var{ch} is a lowercase character.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_UNICODE_ISUPPER}{Py_UNICODE ch}
- Returns 1/0 depending on whether \var{ch} is an uppercase
- character.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_UNICODE_ISTITLE}{Py_UNICODE ch}
- Returns 1/0 depending on whether \var{ch} is a titlecase character.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_UNICODE_ISLINEBREAK}{Py_UNICODE ch}
- Returns 1/0 depending on whether \var{ch} is a linebreak character.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_UNICODE_ISDECIMAL}{Py_UNICODE ch}
- Returns 1/0 depending on whether \var{ch} is a decimal character.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_UNICODE_ISDIGIT}{Py_UNICODE ch}
- Returns 1/0 depending on whether \var{ch} is a digit character.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_UNICODE_ISNUMERIC}{Py_UNICODE ch}
- Returns 1/0 depending on whether \var{ch} is a numeric character.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_UNICODE_ISALPHA}{Py_UNICODE ch}
- Returns 1/0 depending on whether \var{ch} is an alphabetic
- character.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_UNICODE_ISALNUM}{Py_UNICODE ch}
- Returns 1/0 depending on whether \var{ch} is an alphanumeric
- character.
-\end{cfuncdesc}
-
-These APIs can be used for fast direct character conversions:
-
-\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOLOWER}{Py_UNICODE ch}
- Returns the character \var{ch} converted to lower case.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOUPPER}{Py_UNICODE ch}
- Returns the character \var{ch} converted to upper case.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{Py_UNICODE}{Py_UNICODE_TOTITLE}{Py_UNICODE ch}
- Returns the character \var{ch} converted to title case.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_UNICODE_TODECIMAL}{Py_UNICODE ch}
- Returns the character \var{ch} converted to a decimal positive
- integer. Returns \code{-1} if this is not possible. Does not raise
- exceptions.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_UNICODE_TODIGIT}{Py_UNICODE ch}
- Returns the character \var{ch} converted to a single digit integer.
- Returns \code{-1} if this is not possible. Does not raise
- exceptions.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{double}{Py_UNICODE_TONUMERIC}{Py_UNICODE ch}
- Returns the character \var{ch} converted to a (positive) double.
- Returns \code{-1.0} if this is not possible. Does not raise
- exceptions.
-\end{cfuncdesc}
-
-% --- Plain Py_UNICODE ---------------------------------------------------
-
-To create Unicode objects and access their basic sequence properties,
-use these APIs:
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_FromUnicode}{const Py_UNICODE *u,
- int size}
- Create a Unicode Object from the Py_UNICODE buffer \var{u} of the
- given size. \var{u} may be \NULL{} which causes the contents to be
- undefined. It is the user's responsibility to fill in the needed
- data. The buffer is copied into the new object. If the buffer is
- not \NULL, the return value might be a shared object. Therefore,
- modification of the resulting Unicode object is only allowed when
- \var{u} is \NULL.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{Py_UNICODE*}{PyUnicode_AsUnicode}{PyObject *unicode}
- Return a read-only pointer to the Unicode object's internal
- \ctype{Py_UNICODE} buffer, \NULL{} if \var{unicode} is not a Unicode
- object.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyUnicode_GetSize}{PyObject *unicode}
- Return the length of the Unicode object.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_FromEncodedObject}{PyObject *obj,
- const char *encoding,
- const char *errors}
- Coerce an encoded object \var{obj} to an Unicode object and return a
- reference with incremented refcount.
-
- Coercion is done in the following way:
-
-\begin{enumerate}
-\item Unicode objects are passed back as-is with incremented
- refcount. \note{These cannot be decoded; passing a non-\NULL{}
- value for encoding will result in a \exception{TypeError}.}
-
-\item String and other char buffer compatible objects are decoded
- according to the given encoding and using the error handling
- defined by errors. Both can be \NULL{} to have the interface
- use the default values (see the next section for details).
-
-\item All other objects cause an exception.
-\end{enumerate}
-
- The API returns \NULL{} if there was an error. The caller is
- responsible for decref'ing the returned objects.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_FromObject}{PyObject *obj}
- Shortcut for \code{PyUnicode_FromEncodedObject(obj, NULL, "strict")}
- which is used throughout the interpreter whenever coercion to
- Unicode is needed.
-\end{cfuncdesc}
-
-% --- wchar_t support for platforms which support it ---------------------
-
-If the platform supports \ctype{wchar_t} and provides a header file
-wchar.h, Python can interface directly to this type using the
-following functions. Support is optimized if Python's own
-\ctype{Py_UNICODE} type is identical to the system's \ctype{wchar_t}.
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_FromWideChar}{const wchar_t *w,
- int size}
- Create a Unicode object from the \ctype{wchar_t} buffer \var{w} of
- the given size. Returns \NULL{} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyUnicode_AsWideChar}{PyUnicodeObject *unicode,
- wchar_t *w,
- int size}
- Copies the Unicode object contents into the \ctype{wchar_t} buffer
- \var{w}. At most \var{size} \ctype{wchar_t} characters are copied.
- Returns the number of \ctype{wchar_t} characters copied or -1 in
- case of an error.
-\end{cfuncdesc}
-
-
-\subsubsection{Built-in Codecs \label{builtinCodecs}}
-
-Python provides a set of builtin codecs which are written in C
-for speed. All of these codecs are directly usable via the
-following functions.
-
-Many of the following APIs take two arguments encoding and
-errors. These parameters encoding and errors have the same semantics
-as the ones of the builtin unicode() Unicode object constructor.
-
-Setting encoding to \NULL{} causes the default encoding to be used
-which is \ASCII. The file system calls should use
-\cdata{Py_FileSystemDefaultEncoding} as the encoding for file
-names. This variable should be treated as read-only: On some systems,
-it will be a pointer to a static string, on others, it will change at
-run-time, e.g. when the application invokes setlocale.
-
-Error handling is set by errors which may also be set to \NULL{}
-meaning to use the default handling defined for the codec. Default
-error handling for all builtin codecs is ``strict''
-(\exception{ValueError} is raised).
-
-The codecs all use a similar interface. Only deviation from the
-following generic ones are documented for simplicity.
-
-% --- Generic Codecs -----------------------------------------------------
-
-These are the generic codec APIs:
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_Decode}{const char *s,
- int size,
- const char *encoding,
- const char *errors}
- Create a Unicode object by decoding \var{size} bytes of the encoded
- string \var{s}. \var{encoding} and \var{errors} have the same
- meaning as the parameters of the same name in the
- \function{unicode()} builtin function. The codec to be used is
- looked up using the Python codec registry. Returns \NULL{} if an
- exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_Encode}{const Py_UNICODE *s,
- int size,
- const char *encoding,
- const char *errors}
- Encodes the \ctype{Py_UNICODE} buffer of the given size and returns
- a Python string object. \var{encoding} and \var{errors} have the
- same meaning as the parameters of the same name in the Unicode
- \method{encode()} method. The codec to be used is looked up using
- the Python codec registry. Returns \NULL{} if an exception was
- raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_AsEncodedString}{PyObject *unicode,
- const char *encoding,
- const char *errors}
- Encodes a Unicode object and returns the result as Python string
- object. \var{encoding} and \var{errors} have the same meaning as the
- parameters of the same name in the Unicode \method{encode()} method.
- The codec to be used is looked up using the Python codec registry.
- Returns \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-% --- UTF-8 Codecs -------------------------------------------------------
-
-These are the UTF-8 codec APIs:
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF8}{const char *s,
- int size,
- const char *errors}
- Creates a Unicode object by decoding \var{size} bytes of the UTF-8
- encoded string \var{s}. Returns \NULL{} if an exception was raised
- by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF8}{const Py_UNICODE *s,
- int size,
- const char *errors}
- Encodes the \ctype{Py_UNICODE} buffer of the given size using UTF-8
- and returns a Python string object. Returns \NULL{} if an exception
- was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF8String}{PyObject *unicode}
- Encodes a Unicode objects using UTF-8 and returns the result as
- Python string object. Error handling is ``strict''. Returns
- \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-% --- UTF-16 Codecs ------------------------------------------------------ */
-
-These are the UTF-16 codec APIs:
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUTF16}{const char *s,
- int size,
- const char *errors,
- int *byteorder}
- Decodes \var{length} bytes from a UTF-16 encoded buffer string and
- returns the corresponding Unicode object. \var{errors} (if
- non-\NULL) defines the error handling. It defaults to ``strict''.
-
- If \var{byteorder} is non-\NULL, the decoder starts decoding using
- the given byte order:
-
-\begin{verbatim}
- *byteorder == -1: little endian
- *byteorder == 0: native order
- *byteorder == 1: big endian
-\end{verbatim}
-
- and then switches according to all byte order marks (BOM) it finds
- in the input data. BOMs are not copied into the resulting Unicode
- string. After completion, \var{*byteorder} is set to the current
- byte order at the end of input data.
-
- If \var{byteorder} is \NULL, the codec starts in native order mode.
-
- Returns \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUTF16}{const Py_UNICODE *s,
- int size,
- const char *errors,
- int byteorder}
- Returns a Python string object holding the UTF-16 encoded value of
- the Unicode data in \var{s}. If \var{byteorder} is not \code{0},
- output is written according to the following byte order:
-
-\begin{verbatim}
- byteorder == -1: little endian
- byteorder == 0: native byte order (writes a BOM mark)
- byteorder == 1: big endian
-\end{verbatim}
-
- If byteorder is \code{0}, the output string will always start with
- the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark
- is prepended.
-
- Note that \ctype{Py_UNICODE} data is being interpreted as UTF-16
- reduced to UCS-2. This trick makes it possible to add full UTF-16
- capabilities at a later point without comprimising the APIs.
-
- Returns \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUTF16String}{PyObject *unicode}
- Returns a Python string using the UTF-16 encoding in native byte
- order. The string always starts with a BOM mark. Error handling is
- ``strict''. Returns \NULL{} if an exception was raised by the
- codec.
-\end{cfuncdesc}
-
-% --- Unicode-Escape Codecs ----------------------------------------------
-
-These are the ``Unicode Esacpe'' codec APIs:
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeUnicodeEscape}{const char *s,
- int size,
- const char *errors}
- Creates a Unicode object by decoding \var{size} bytes of the
- Unicode-Escape encoded string \var{s}. Returns \NULL{} if an
- exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeUnicodeEscape}{const Py_UNICODE *s,
- int size,
- const char *errors}
- Encodes the \ctype{Py_UNICODE} buffer of the given size using
- Unicode-Escape and returns a Python string object. Returns \NULL{}
- if an exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_AsUnicodeEscapeString}{PyObject *unicode}
- Encodes a Unicode objects using Unicode-Escape and returns the
- result as Python string object. Error handling is ``strict''.
- Returns \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-% --- Raw-Unicode-Escape Codecs ------------------------------------------
-
-These are the ``Raw Unicode Esacpe'' codec APIs:
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeRawUnicodeEscape}{const char *s,
- int size,
- const char *errors}
- Creates a Unicode object by decoding \var{size} bytes of the
- Raw-Unicode-Esacpe encoded string \var{s}. Returns \NULL{} if an
- exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeRawUnicodeEscape}{const Py_UNICODE *s,
- int size,
- const char *errors}
- Encodes the \ctype{Py_UNICODE} buffer of the given size using
- Raw-Unicode-Escape and returns a Python string object. Returns
- \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_AsRawUnicodeEscapeString}{PyObject *unicode}
- Encodes a Unicode objects using Raw-Unicode-Escape and returns the
- result as Python string object. Error handling is ``strict''.
- Returns \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-% --- Latin-1 Codecs -----------------------------------------------------
-
-These are the Latin-1 codec APIs:
-Latin-1 corresponds to the first 256 Unicode ordinals and only these
-are accepted by the codecs during encoding.
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeLatin1}{const char *s,
- int size,
- const char *errors}
- Creates a Unicode object by decoding \var{size} bytes of the Latin-1
- encoded string \var{s}. Returns \NULL{} if an exception was raised
- by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeLatin1}{const Py_UNICODE *s,
- int size,
- const char *errors}
- Encodes the \ctype{Py_UNICODE} buffer of the given size using
- Latin-1 and returns a Python string object. Returns \NULL{} if an
- exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_AsLatin1String}{PyObject *unicode}
- Encodes a Unicode objects using Latin-1 and returns the result as
- Python string object. Error handling is ``strict''. Returns
- \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-% --- ASCII Codecs -------------------------------------------------------
-
-These are the \ASCII{} codec APIs. Only 7-bit \ASCII{} data is
-accepted. All other codes generate errors.
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeASCII}{const char *s,
- int size,
- const char *errors}
- Creates a Unicode object by decoding \var{size} bytes of the
- \ASCII{} encoded string \var{s}. Returns \NULL{} if an exception
- was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeASCII}{const Py_UNICODE *s,
- int size,
- const char *errors}
- Encodes the \ctype{Py_UNICODE} buffer of the given size using
- \ASCII{} and returns a Python string object. Returns \NULL{} if an
- exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_AsASCIIString}{PyObject *unicode}
- Encodes a Unicode objects using \ASCII{} and returns the result as
- Python string object. Error handling is ``strict''. Returns
- \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-% --- Character Map Codecs -----------------------------------------------
-
-These are the mapping codec APIs:
-
-This codec is special in that it can be used to implement many
-different codecs (and this is in fact what was done to obtain most of
-the standard codecs included in the \module{encodings} package). The
-codec uses mapping to encode and decode characters.
-
-Decoding mappings must map single string characters to single Unicode
-characters, integers (which are then interpreted as Unicode ordinals)
-or None (meaning "undefined mapping" and causing an error).
-
-Encoding mappings must map single Unicode characters to single string
-characters, integers (which are then interpreted as Latin-1 ordinals)
-or None (meaning "undefined mapping" and causing an error).
-
-The mapping objects provided must only support the __getitem__ mapping
-interface.
-
-If a character lookup fails with a LookupError, the character is
-copied as-is meaning that its ordinal value will be interpreted as
-Unicode or Latin-1 ordinal resp. Because of this, mappings only need
-to contain those mappings which map characters to different code
-points.
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeCharmap}{const char *s,
- int size,
- PyObject *mapping,
- const char *errors}
- Creates a Unicode object by decoding \var{size} bytes of the encoded
- string \var{s} using the given \var{mapping} object. Returns
- \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeCharmap}{const Py_UNICODE *s,
- int size,
- PyObject *mapping,
- const char *errors}
- Encodes the \ctype{Py_UNICODE} buffer of the given size using the
- given \var{mapping} object and returns a Python string object.
- Returns \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_AsCharmapString}{PyObject *unicode,
- PyObject *mapping}
- Encodes a Unicode objects using the given \var{mapping} object and
- returns the result as Python string object. Error handling is
- ``strict''. Returns \NULL{} if an exception was raised by the
- codec.
-\end{cfuncdesc}
-
-The following codec API is special in that maps Unicode to Unicode.
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_TranslateCharmap}{const Py_UNICODE *s,
- int size,
- PyObject *table,
- const char *errors}
- Translates a \ctype{Py_UNICODE} buffer of the given length by
- applying a character mapping \var{table} to it and returns the
- resulting Unicode object. Returns \NULL{} when an exception was
- raised by the codec.
-
- The \var{mapping} table must map Unicode ordinal integers to Unicode
- ordinal integers or None (causing deletion of the character).
-
- Mapping tables need only provide the method{__getitem__()}
- interface; dictionaries and sequences work well. Unmapped character
- ordinals (ones which cause a \exception{LookupError}) are left
- untouched and are copied as-is.
-\end{cfuncdesc}
-
-% --- MBCS codecs for Windows --------------------------------------------
-
-These are the MBCS codec APIs. They are currently only available on
-Windows and use the Win32 MBCS converters to implement the
-conversions. Note that MBCS (or DBCS) is a class of encodings, not
-just one. The target encoding is defined by the user settings on the
-machine running the codec.
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_DecodeMBCS}{const char *s,
- int size,
- const char *errors}
- Creates a Unicode object by decoding \var{size} bytes of the MBCS
- encoded string \var{s}. Returns \NULL{} if an exception was
- raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_EncodeMBCS}{const Py_UNICODE *s,
- int size,
- const char *errors}
- Encodes the \ctype{Py_UNICODE} buffer of the given size using MBCS
- and returns a Python string object. Returns \NULL{} if an exception
- was raised by the codec.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_AsMBCSString}{PyObject *unicode}
- Encodes a Unicode objects using MBCS and returns the result as
- Python string object. Error handling is ``strict''. Returns
- \NULL{} if an exception was raised by the codec.
-\end{cfuncdesc}
-
-% --- Methods & Slots ----------------------------------------------------
-
-\subsubsection{Methods and Slot Functions \label{unicodeMethodsAndSlots}}
-
-The following APIs are capable of handling Unicode objects and strings
-on input (we refer to them as strings in the descriptions) and return
-Unicode objects or integers as apporpriate.
-
-They all return \NULL{} or \code{-1} if an exception occurs.
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_Concat}{PyObject *left,
- PyObject *right}
- Concat two strings giving a new Unicode string.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_Split}{PyObject *s,
- PyObject *sep,
- int maxsplit}
- Split a string giving a list of Unicode strings. If sep is \NULL,
- splitting will be done at all whitespace substrings. Otherwise,
- splits occur at the given separator. At most \var{maxsplit} splits
- will be done. If negative, no limit is set. Separators are not
- included in the resulting list.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_Splitlines}{PyObject *s,
- int keepend}
- Split a Unicode string at line breaks, returning a list of Unicode
- strings. CRLF is considered to be one line break. If \var{keepend}
- is 0, the Line break characters are not included in the resulting
- strings.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_Translate}{PyObject *str,
- PyObject *table,
- const char *errors}
- Translate a string by applying a character mapping table to it and
- return the resulting Unicode object.
-
- The mapping table must map Unicode ordinal integers to Unicode
- ordinal integers or None (causing deletion of the character).
-
- Mapping tables need only provide the \method{__getitem__()}
- interface; dictionaries and sequences work well. Unmapped character
- ordinals (ones which cause a \exception{LookupError}) are left
- untouched and are copied as-is.
-
- \var{errors} has the usual meaning for codecs. It may be \NULL{}
- which indicates to use the default error handling.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_Join}{PyObject *separator,
- PyObject *seq}
- Join a sequence of strings using the given separator and return the
- resulting Unicode string.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_Tailmatch}{PyObject *str,
- PyObject *substr,
- int start,
- int end,
- int direction}
- Return 1 if \var{substr} matches \var{str}[\var{start}:\var{end}] at
- the given tail end (\var{direction} == -1 means to do a prefix
- match, \var{direction} == 1 a suffix match), 0 otherwise.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyUnicode_Find}{PyObject *str,
- PyObject *substr,
- int start,
- int end,
- int direction}
- Return the first position of \var{substr} in
- \var{str}[\var{start}:\var{end}] using the given \var{direction}
- (\var{direction} == 1 means to do a forward search,
- \var{direction} == -1 a backward search). The return value is the
- index of the first match; a value of \code{-1} indicates that no
- match was found, and \code{-2} indicates that an error occurred and
- an exception has been set.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyUnicode_Count}{PyObject *str,
- PyObject *substr,
- int start,
- int end}
- Return the number of non-overlapping occurrences of \var{substr} in
- \code{\var{str}[\var{start}:\var{end}]}. Returns \code{-1} if an
- error occurred.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_Replace}{PyObject *str,
- PyObject *substr,
- PyObject *replstr,
- int maxcount}
- Replace at most \var{maxcount} occurrences of \var{substr} in
- \var{str} with \var{replstr} and return the resulting Unicode object.
- \var{maxcount} == -1 means replace all occurrences.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyUnicode_Compare}{PyObject *left, PyObject *right}
- Compare two strings and return -1, 0, 1 for less than, equal, and
- greater than, respectively.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
- PyObject *args}
- Returns a new string object from \var{format} and \var{args}; this
- is analogous to \code{\var{format} \%\ \var{args}}. The
- \var{args} argument must be a tuple.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyUnicode_Contains}{PyObject *container,
- PyObject *element}
- Checks whether \var{element} is contained in \var{container} and
- returns true or false accordingly.
-
- \var{element} has to coerce to a one element Unicode
- string. \code{-1} is returned if there was an error.
-\end{cfuncdesc}
-
-
-\subsection{Buffer Objects \label{bufferObjects}}
-\sectionauthor{Greg Stein}{gstein@lyra.org}
-
-\obindex{buffer}
-Python objects implemented in C can export a group of functions called
-the ``buffer\index{buffer interface} interface.'' These functions can
-be used by an object to expose its data in a raw, byte-oriented
-format. Clients of the object can use the buffer interface to access
-the object data directly, without needing to copy it first.
-
-Two examples of objects that support
-the buffer interface are strings and arrays. The string object exposes
-the character contents in the buffer interface's byte-oriented
-form. An array can also expose its contents, but it should be noted
-that array elements may be multi-byte values.
-
-An example user of the buffer interface is the file object's
-\method{write()} method. Any object that can export a series of bytes
-through the buffer interface can be written to a file. There are a
-number of format codes to \cfunction{PyArg_ParseTuple()} that operate
-against an object's buffer interface, returning data from the target
-object.
-
-More information on the buffer interface is provided in the section
-``Buffer Object Structures'' (section~\ref{buffer-structs}), under
-the description for \ctype{PyBufferProcs}\ttindex{PyBufferProcs}.
-
-A ``buffer object'' is defined in the \file{bufferobject.h} header
-(included by \file{Python.h}). These objects look very similar to
-string objects at the Python programming level: they support slicing,
-indexing, concatenation, and some other standard string
-operations. However, their data can come from one of two sources: from
-a block of memory, or from another object which exports the buffer
-interface.
-
-Buffer objects are useful as a way to expose the data from another
-object's buffer interface to the Python programmer. They can also be
-used as a zero-copy slicing mechanism. Using their ability to
-reference a block of memory, it is possible to expose any data to the
-Python programmer quite easily. The memory could be a large, constant
-array in a C extension, it could be a raw block of memory for
-manipulation before passing to an operating system library, or it
-could be used to pass around structured data in its native, in-memory
-format.
-
-\begin{ctypedesc}{PyBufferObject}
- This subtype of \ctype{PyObject} represents a buffer object.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
- The instance of \ctype{PyTypeObject} which represents the Python
- buffer type; it is the same object as \code{types.BufferType} in the
- Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
-\end{cvardesc}
-
-\begin{cvardesc}{int}{Py_END_OF_BUFFER}
- This constant may be passed as the \var{size} parameter to
- \cfunction{PyBuffer_FromObject()} or
- \cfunction{PyBuffer_FromReadWriteObject()}. It indicates that the
- new \ctype{PyBufferObject} should refer to \var{base} object from
- the specified \var{offset} to the end of its exported buffer. Using
- this enables the caller to avoid querying the \var{base} object for
- its length.
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyBuffer_Check}{PyObject *p}
- Return true if the argument has type \cdata{PyBuffer_Type}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyBuffer_FromObject}{PyObject *base,
- int offset, int size}
- Return a new read-only buffer object. This raises
- \exception{TypeError} if \var{base} doesn't support the read-only
- buffer protocol or doesn't provide exactly one buffer segment, or it
- raises \exception{ValueError} if \var{offset} is less than zero. The
- buffer will hold a reference to the \var{base} object, and the
- buffer's contents will refer to the \var{base} object's buffer
- interface, starting as position \var{offset} and extending for
- \var{size} bytes. If \var{size} is \constant{Py_END_OF_BUFFER}, then
- the new buffer's contents extend to the length of the \var{base}
- object's exported buffer data.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteObject}{PyObject *base,
- int offset,
- int size}
- Return a new writable buffer object. Parameters and exceptions are
- similar to those for \cfunction{PyBuffer_FromObject()}. If the
- \var{base} object does not export the writeable buffer protocol,
- then \exception{TypeError} is raised.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyBuffer_FromMemory}{void *ptr, int size}
- Return a new read-only buffer object that reads from a specified
- location in memory, with a specified size. The caller is
- responsible for ensuring that the memory buffer, passed in as
- \var{ptr}, is not deallocated while the returned buffer object
- exists. Raises \exception{ValueError} if \var{size} is less than
- zero. Note that \constant{Py_END_OF_BUFFER} may \emph{not} be
- passed for the \var{size} parameter; \exception{ValueError} will be
- raised in that case.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyBuffer_FromReadWriteMemory}{void *ptr, int size}
- Similar to \cfunction{PyBuffer_FromMemory()}, but the returned
- buffer is writable.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyBuffer_New}{int size}
- Returns a new writable buffer object that maintains its own memory
- buffer of \var{size} bytes. \exception{ValueError} is returned if
- \var{size} is not zero or positive.
-\end{cfuncdesc}
-
-
-\subsection{Tuple Objects \label{tupleObjects}}
-
-\obindex{tuple}
-\begin{ctypedesc}{PyTupleObject}
- This subtype of \ctype{PyObject} represents a Python tuple object.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyTypeObject}{PyTuple_Type}
- This instance of \ctype{PyTypeObject} represents the Python tuple
- type; it is the same object as \code{types.TupleType} in the Python
- layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
- Return true if \var{p} is a tuple object or an instance of a subtype
- of the tuple type.
- \versionchanged[Allowed subtypes to be accepted]{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyTuple_CheckExact}{PyObject *p}
- Return true if \var{p} is a tuple object, but not an instance of a
- subtype of the tuple type.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyTuple_New}{int len}
- Return a new tuple object of size \var{len}, or \NULL{} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyTuple_Size}{PyObject *p}
- Takes a pointer to a tuple object, and returns the size of that
- tuple.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyTuple_GET_SIZE}{PyObject *p}
- Return the size of the tuple \var{p}, which must be non-\NULL{} and
- point to a tuple; no error checking is performed.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyTuple_GetItem}{PyObject *p, int pos}
- Returns the object at position \var{pos} in the tuple pointed to by
- \var{p}. If \var{pos} is out of bounds, returns \NULL{} and sets an
- \exception{IndexError} exception.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyTuple_GET_ITEM}{PyObject *p, int pos}
- Like \cfunction{PyTuple_GetItem()}, but does no checking of its
- arguments.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyTuple_GetSlice}{PyObject *p,
- int low, int high}
- Takes a slice of the tuple pointed to by \var{p} from \var{low} to
- \var{high} and returns it as a new tuple.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyTuple_SetItem}{PyObject *p,
- int pos, PyObject *o}
- Inserts a reference to object \var{o} at position \var{pos} of the
- tuple pointed to by \var{p}. It returns \code{0} on success.
- \note{This function ``steals'' a reference to \var{o}.}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyTuple_SET_ITEM}{PyObject *p,
- int pos, PyObject *o}
- Like \cfunction{PyTuple_SetItem()}, but does no error checking, and
- should \emph{only} be used to fill in brand new tuples. \note{This
- function ``steals'' a reference to \var{o}.}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{_PyTuple_Resize}{PyObject **p, int newsize}
- Can be used to resize a tuple. \var{newsize} will be the new length
- of the tuple. Because tuples are \emph{supposed} to be immutable,
- this should only be used if there is only one reference to the
- object. Do \emph{not} use this if the tuple may already be known to
- some other part of the code. The tuple will always grow or shrink
- at the end. Think of this as destroying the old tuple and creating
- a new one, only more efficiently. Returns \code{0} on success.
- Client code should never assume that the resulting value of
- \code{*\var{p}} will be the same as before calling this function.
- If the object referenced by \code{*\var{p}} is replaced, the
- original \code{*\var{p}} is destroyed. On failure, returns
- \code{-1} and sets \code{*\var{p}} to \NULL, and raises
- \exception{MemoryError} or
- \exception{SystemError}.
- \versionchanged[Removed unused third parameter, \var{last_is_sticky}]{2.2}
-\end{cfuncdesc}
-
-
-\subsection{List Objects \label{listObjects}}
-
-\obindex{list}
-\begin{ctypedesc}{PyListObject}
- This subtype of \ctype{PyObject} represents a Python list object.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyTypeObject}{PyList_Type}
- This instance of \ctype{PyTypeObject} represents the Python list
- type. This is the same object as \code{types.ListType}.
- \withsubitem{(in module types)}{\ttindex{ListType}}
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
- Returns true if its argument is a \ctype{PyListObject}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyList_New}{int len}
- Returns a new list of length \var{len} on success, or \NULL{} on
- failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyList_Size}{PyObject *list}
- Returns the length of the list object in \var{list}; this is
- equivalent to \samp{len(\var{list})} on a list object.
- \bifuncindex{len}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyList_GET_SIZE}{PyObject *list}
- Macro form of \cfunction{PyList_Size()} without error checking.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyList_GetItem}{PyObject *list, int index}
- Returns the object at position \var{pos} in the list pointed to by
- \var{p}. If \var{pos} is out of bounds, returns \NULL{} and sets an
- \exception{IndexError} exception.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyList_GET_ITEM}{PyObject *list, int i}
- Macro form of \cfunction{PyList_GetItem()} without error checking.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index,
- PyObject *item}
- Sets the item at index \var{index} in list to \var{item}. Returns
- \code{0} on success or \code{-1} on failure. \note{This function
- ``steals'' a reference to \var{item} and discards a reference to an
- item already in the list at the affected position.}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyList_SET_ITEM}{PyObject *list, int i,
- PyObject *o}
- Macro form of \cfunction{PyList_SetItem()} without error checking.
- This is normally only used to fill in new lists where there is no
- previous content.
- \note{This function ``steals'' a reference to \var{item}, and,
- unlike \cfunction{PyList_SetItem()}, does \emph{not} discard a
- reference to any item that it being replaced; any reference in
- \var{list} at position \var{i} will be leaked.}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index,
- PyObject *item}
- Inserts the item \var{item} into list \var{list} in front of index
- \var{index}. Returns \code{0} if successful; returns \code{-1} and
- raises an exception if unsuccessful. Analogous to
- \code{\var{list}.insert(\var{index}, \var{item})}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyList_Append}{PyObject *list, PyObject *item}
- Appends the object \var{item} at the end of list \var{list}.
- Returns \code{0} if successful; returns \code{-1} and sets an
- exception if unsuccessful. Analogous to
- \code{\var{list}.append(\var{item})}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyList_GetSlice}{PyObject *list,
- int low, int high}
- Returns a list of the objects in \var{list} containing the objects
- \emph{between} \var{low} and \var{high}. Returns \NULL{} and sets
- an exception if unsuccessful.
- Analogous to \code{\var{list}[\var{low}:\var{high}]}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyList_SetSlice}{PyObject *list,
- int low, int high,
- PyObject *itemlist}
- Sets the slice of \var{list} between \var{low} and \var{high} to the
- contents of \var{itemlist}. Analogous to
- \code{\var{list}[\var{low}:\var{high}] = \var{itemlist}}. Returns
- \code{0} on success, \code{-1} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyList_Sort}{PyObject *list}
- Sorts the items of \var{list} in place. Returns \code{0} on
- success, \code{-1} on failure. This is equivalent to
- \samp{\var{list}.sort()}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyList_Reverse}{PyObject *list}
- Reverses the items of \var{list} in place. Returns \code{0} on
- success, \code{-1} on failure. This is the equivalent of
- \samp{\var{list}.reverse()}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyList_AsTuple}{PyObject *list}
- Returns a new tuple object containing the contents of \var{list};
- equivalent to \samp{tuple(\var{list})}.\bifuncindex{tuple}
-\end{cfuncdesc}
-
-
-\section{Mapping Objects \label{mapObjects}}
-
-\obindex{mapping}
-
-
-\subsection{Dictionary Objects \label{dictObjects}}
-
-\obindex{dictionary}
-\begin{ctypedesc}{PyDictObject}
- This subtype of \ctype{PyObject} represents a Python dictionary
- object.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyTypeObject}{PyDict_Type}
- This instance of \ctype{PyTypeObject} represents the Python
- dictionary type. This is exposed to Python programs as
- \code{types.DictType} and \code{types.DictionaryType}.
- \withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyDict_Check}{PyObject *p}
- Returns true if its argument is a \ctype{PyDictObject}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyDict_New}{}
- Returns a new empty dictionary, or \NULL{} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyDictProxy_New}{PyObject *dict}
- Return a proxy object for a mapping which enforces read-only
- behavior. This is normally used to create a proxy to prevent
- modification of the dictionary for non-dynamic class types.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyDict_Clear}{PyObject *p}
- Empties an existing dictionary of all key-value pairs.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyDict_Copy}{PyObject *p}
- Returns a new dictionary that contains the same key-value pairs as
- \var{p}.
- \versionadded{1.6}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key,
- PyObject *val}
- Inserts \var{value} into the dictionary \var{p} with a key of
- \var{key}. \var{key} must be hashable; if it isn't,
- \exception{TypeError} will be raised.
- Returns \code{0} on success or \code{-1} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyDict_SetItemString}{PyObject *p,
- char *key,
- PyObject *val}
- Inserts \var{value} into the dictionary \var{p} using \var{key} as a
- key. \var{key} should be a \ctype{char*}. The key object is created
- using \code{PyString_FromString(\var{key})}. Returns \code{0} on
- success or \code{-1} on failure.
- \ttindex{PyString_FromString()}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyDict_DelItem}{PyObject *p, PyObject *key}
- Removes the entry in dictionary \var{p} with key \var{key}.
- \var{key} must be hashable; if it isn't, \exception{TypeError} is
- raised. Returns \code{0} on success or \code{-1} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key}
- Removes the entry in dictionary \var{p} which has a key specified by
- the string \var{key}. Returns \code{0} on success or \code{-1} on
- failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key}
- Returns the object from dictionary \var{p} which has a key
- \var{key}. Returns \NULL{} if the key \var{key} is not present, but
- \emph{without} setting an exception.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyDict_GetItemString}{PyObject *p, char *key}
- This is the same as \cfunction{PyDict_GetItem()}, but \var{key} is
- specified as a \ctype{char*}, rather than a \ctype{PyObject*}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyDict_Items}{PyObject *p}
- Returns a \ctype{PyListObject} containing all the items from the
- dictionary, as in the dictinoary method \method{items()} (see the
- \citetitle[../lib/lib.html]{Python Library Reference}).
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyDict_Keys}{PyObject *p}
- Returns a \ctype{PyListObject} containing all the keys from the
- dictionary, as in the dictionary method \method{keys()} (see the
- \citetitle[../lib/lib.html]{Python Library Reference}).
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyDict_Values}{PyObject *p}
- Returns a \ctype{PyListObject} containing all the values from the
- dictionary \var{p}, as in the dictionary method \method{values()}
- (see the \citetitle[../lib/lib.html]{Python Library Reference}).
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyDict_Size}{PyObject *p}
- Returns the number of items in the dictionary. This is equivalent
- to \samp{len(\var{p})} on a dictionary.\bifuncindex{len}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyDict_Next}{PyObject *p, int *ppos,
- PyObject **pkey, PyObject **pvalue}
- Iterate over all key-value pairs in the dictionary \var{p}. The
- \ctype{int} referred to by \var{ppos} must be initialized to
- \code{0} prior to the first call to this function to start the
- iteration; the function returns true for each pair in the
- dictionary, and false once all pairs have been reported. The
- parameters \var{pkey} and \var{pvalue} should either point to
- \ctype{PyObject*} variables that will be filled in with each key and
- value, respectively, or may be \NULL. Any references returned through
- them are borrowed.
-
- For example:
-
-\begin{verbatim}
-PyObject *key, *value;
-int pos = 0;
-
-while (PyDict_Next(self->dict, &pos, &key, &value)) {
- /* do something interesting with the values... */
- ...
-}
-\end{verbatim}
-
- The dictionary \var{p} should not be mutated during iteration. It
- is safe (since Python 2.1) to modify the values of the keys as you
- iterate over the dictionary, but only so long as the set of keys
- does not change. For example:
-
-\begin{verbatim}
-PyObject *key, *value;
-int pos = 0;
-
-while (PyDict_Next(self->dict, &pos, &key, &value)) {
- int i = PyInt_AS_LONG(value) + 1;
- PyObject *o = PyInt_FromLong(i);
- if (o == NULL)
- return -1;
- if (PyDict_SetItem(self->dict, key, o) < 0) {
- Py_DECREF(o);
- return -1;
- }
- Py_DECREF(o);
-}
-\end{verbatim}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyDict_Merge}{PyObject *a, PyObject *b, int override}
- Iterate over mapping object \var{b} adding key-value pairs to dictionary
- \var{a}.
- \var{b} may be a dictionary, or any object supporting
- \function{PyMapping_Keys()} and \function{PyObject_GetItem()}.
- If \var{override} is true, existing pairs in \var{a} will
- be replaced if a matching key is found in \var{b}, otherwise pairs
- will only be added if there is not a matching key in \var{a}.
- Return \code{0} on success or \code{-1} if an exception was
- raised.
-\versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyDict_Update}{PyObject *a, PyObject *b}
- This is the same as \code{PyDict_Merge(\var{a}, \var{b}, 1)} in C,
- or \code{\var{a}.update(\var{b})} in Python. Return \code{0} on
- success or \code{-1} if an exception was raised.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyDict_MergeFromSeq2}{PyObject *a, PyObject *seq2,
- int override}
- Update or merge into dictionary \var{a}, from the key-value pairs in
- \var{seq2}. \var{seq2} must be an iterable object producing
- iterable objects of length 2, viewed as key-value pairs. In case of
- duplicate keys, the last wins if \var{override} is true, else the
- first wins.
- Return \code{0} on success or \code{-1} if an exception
- was raised.
- Equivalent Python (except for the return value):
-
-\begin{verbatim}
-def PyDict_MergeFromSeq2(a, seq2, override):
- for key, value in seq2:
- if override or key not in a:
- a[key] = value
-\end{verbatim}
-
- \versionadded{2.2}
-\end{cfuncdesc}
-
-
-\section{Other Objects \label{otherObjects}}
-
-\subsection{File Objects \label{fileObjects}}
-
-\obindex{file}
-Python's built-in file objects are implemented entirely on the
-\ctype{FILE*} support from the C standard library. This is an
-implementation detail and may change in future releases of Python.
-
-\begin{ctypedesc}{PyFileObject}
- This subtype of \ctype{PyObject} represents a Python file object.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyTypeObject}{PyFile_Type}
- This instance of \ctype{PyTypeObject} represents the Python file
- type. This is exposed to Python programs as \code{types.FileType}.
- \withsubitem{(in module types)}{\ttindex{FileType}}
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyFile_Check}{PyObject *p}
- Returns true if its argument is a \ctype{PyFileObject} or a subtype
- of \ctype{PyFileObject}.
- \versionchanged[Allowed subtypes to be accepted]{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyFile_CheckExact}{PyObject *p}
- Returns true if its argument is a \ctype{PyFileObject}, but not a
- subtype of \ctype{PyFileObject}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyFile_FromString}{char *filename, char *mode}
- On success, returns a new file object that is opened on the file
- given by \var{filename}, with a file mode given by \var{mode}, where
- \var{mode} has the same semantics as the standard C routine
- \cfunction{fopen()}\ttindex{fopen()}. On failure, returns \NULL.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyFile_FromFile}{FILE *fp,
- char *name, char *mode,
- int (*close)(FILE*)}
- Creates a new \ctype{PyFileObject} from the already-open standard C
- file pointer, \var{fp}. The function \var{close} will be called
- when the file should be closed. Returns \NULL{} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{FILE*}{PyFile_AsFile}{PyFileObject *p}
- Returns the file object associated with \var{p} as a \ctype{FILE*}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyFile_GetLine}{PyObject *p, int n}
- Equivalent to \code{\var{p}.readline(\optional{\var{n}})}, this
- function reads one line from the object \var{p}. \var{p} may be a
- file object or any object with a \method{readline()} method. If
- \var{n} is \code{0}, exactly one line is read, regardless of the
- length of the line. If \var{n} is greater than \code{0}, no more
- than \var{n} bytes will be read from the file; a partial line can be
- returned. In both cases, an empty string is returned if the end of
- the file is reached immediately. If \var{n} is less than \code{0},
- however, one line is read regardless of length, but
- \exception{EOFError} is raised if the end of the file is reached
- immediately.
- \withsubitem{(built-in exception)}{\ttindex{EOFError}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyFile_Name}{PyObject *p}
- Returns the name of the file specified by \var{p} as a string
- object.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyFile_SetBufSize}{PyFileObject *p, int n}
- Available on systems with \cfunction{setvbuf()}\ttindex{setvbuf()}
- only. This should only be called immediately after file object
- creation.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyFile_Encoding}{PyFileObject *p, char *enc}
- Set the file's encoding for Unicode output to \var{enc}. Return
- 1 on success and 0 on failure.
- \versionadded{2.3}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyFile_SoftSpace}{PyObject *p, int newflag}
- This function exists for internal use by the interpreter. Sets the
- \member{softspace} attribute of \var{p} to \var{newflag} and
- \withsubitem{(file attribute)}{\ttindex{softspace}}returns the
- previous value. \var{p} does not have to be a file object for this
- function to work properly; any object is supported (thought its only
- interesting if the \member{softspace} attribute can be set). This
- function clears any errors, and will return \code{0} as the previous
- value if the attribute either does not exist or if there were errors
- in retrieving it. There is no way to detect errors from this
- function, but doing so should not be needed.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyFile_WriteObject}{PyObject *obj, PyFileObject *p,
- int flags}
- Writes object \var{obj} to file object \var{p}. The only supported
- flag for \var{flags} is
- \constant{Py_PRINT_RAW}\ttindex{Py_PRINT_RAW}; if given, the
- \function{str()} of the object is written instead of the
- \function{repr()}. Returns \code{0} on success or \code{-1} on
- failure; the appropriate exception will be set.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyFile_WriteString}{const char *s, PyFileObject *p}
- Writes string \var{s} to file object \var{p}. Returns \code{0} on
- success or \code{-1} on failure; the appropriate exception will be
- set.
-\end{cfuncdesc}
-
-
-\subsection{Instance Objects \label{instanceObjects}}
-
-\obindex{instance}
-There are very few functions specific to instance objects.
-
-\begin{cvardesc}{PyTypeObject}{PyInstance_Type}
- Type object for class instances.
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyInstance_Check}{PyObject *obj}
- Returns true if \var{obj} is an instance.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyInstance_New}{PyObject *class,
- PyObject *arg,
- PyObject *kw}
- Create a new instance of a specific class. The parameters \var{arg}
- and \var{kw} are used as the positional and keyword parameters to
- the object's constructor.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyInstance_NewRaw}{PyObject *class,
- PyObject *dict}
- Create a new instance of a specific class without calling it's
- constructor. \var{class} is the class of new object. The
- \var{dict} parameter will be used as the object's \member{__dict__};
- if \NULL, a new dictionary will be created for the instance.
-\end{cfuncdesc}
-
-
-\subsection{Method Objects \label{method-objects}}
-
-\obindex{method}
-There are some useful functions that are useful for working with
-method objects.
-
-\begin{cvardesc}{PyTypeObject}{PyMethod_Type}
- This instance of \ctype{PyTypeObject} represents the Python method
- type. This is exposed to Python programs as \code{types.MethodType}.
- \withsubitem{(in module types)}{\ttindex{MethodType}}
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyMethod_Check}{PyObject *o}
- Return true if \var{o} is a method object (has type
- \cdata{PyMethod_Type}). The parameter must not be \NULL.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyMethod_New}{PyObject *func.
- PyObject *self, PyObject *class}
- Return a new method object, with \var{func} being any callable
- object; this is the function that will be called when the method is
- called. If this method should be bound to an instance, \var{self}
- should be the instance and \var{class} should be the class of
- \var{self}, otherwise \var{self} should be \NULL{} and \var{class}
- should be the class which provides the unbound method..
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyMethod_Class}{PyObject *meth}
- Return the class object from which the method \var{meth} was
- created; if this was created from an instance, it will be the class
- of the instance.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyMethod_GET_CLASS}{PyObject *meth}
- Macro version of \cfunction{PyMethod_Class()} which avoids error
- checking.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyMethod_Function}{PyObject *meth}
- Return the function object associated with the method \var{meth}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyMethod_GET_FUNCTION}{PyObject *meth}
- Macro version of \cfunction{PyMethod_Function()} which avoids error
- checking.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyMethod_Self}{PyObject *meth}
- Return the instance associated with the method \var{meth} if it is
- bound, otherwise return \NULL.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyMethod_GET_SELF}{PyObject *meth}
- Macro version of \cfunction{PyMethod_Self()} which avoids error
- checking.
-\end{cfuncdesc}
-
-
-\subsection{Module Objects \label{moduleObjects}}
-
-\obindex{module}
-There are only a few functions special to module objects.
-
-\begin{cvardesc}{PyTypeObject}{PyModule_Type}
- This instance of \ctype{PyTypeObject} represents the Python module
- type. This is exposed to Python programs as
- \code{types.ModuleType}.
- \withsubitem{(in module types)}{\ttindex{ModuleType}}
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyModule_Check}{PyObject *p}
- Returns true if \var{p} is a module object, or a subtype of a module
- object.
- \versionchanged[Allowed subtypes to be accepted]{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyModule_CheckExact}{PyObject *p}
- Returns true if \var{p} is a module object, but not a subtype of
- \cdata{PyModule_Type}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyModule_New}{char *name}
- Return a new module object with the \member{__name__} attribute set
- to \var{name}. Only the module's \member{__doc__} and
- \member{__name__} attributes are filled in; the caller is
- responsible for providing a \member{__file__} attribute.
- \withsubitem{(module attribute)}{
- \ttindex{__name__}\ttindex{__doc__}\ttindex{__file__}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyModule_GetDict}{PyObject *module}
- Return the dictionary object that implements \var{module}'s
- namespace; this object is the same as the \member{__dict__}
- attribute of the module object. This function never fails.
- \withsubitem{(module attribute)}{\ttindex{__dict__}}
- It is recommended extensions use other \cfunction{PyModule_*()}
- and \cfunction{PyObject_*()} functions rather than directly
- manipulate a module's \member{__dict__}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{char*}{PyModule_GetName}{PyObject *module}
- Return \var{module}'s \member{__name__} value. If the module does
- not provide one, or if it is not a string, \exception{SystemError}
- is raised and \NULL{} is returned.
- \withsubitem{(module attribute)}{\ttindex{__name__}}
- \withsubitem{(built-in exception)}{\ttindex{SystemError}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{char*}{PyModule_GetFilename}{PyObject *module}
- Return the name of the file from which \var{module} was loaded using
- \var{module}'s \member{__file__} attribute. If this is not defined,
- or if it is not a string, raise \exception{SystemError} and return
- \NULL.
- \withsubitem{(module attribute)}{\ttindex{__file__}}
- \withsubitem{(built-in exception)}{\ttindex{SystemError}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyModule_AddObject}{PyObject *module,
- char *name, PyObject *value}
- Add an object to \var{module} as \var{name}. This is a convenience
- function which can be used from the module's initialization
- function. This steals a reference to \var{value}. Returns
- \code{-1} on error, \code{0} on success.
- \versionadded{2.0}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyModule_AddIntConstant}{PyObject *module,
- char *name, int value}
- Add an integer constant to \var{module} as \var{name}. This
- convenience function can be used from the module's initialization
- function. Returns \code{-1} on error, \code{0} on success.
- \versionadded{2.0}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyModule_AddStringConstant}{PyObject *module,
- char *name, char *value}
- Add a string constant to \var{module} as \var{name}. This
- convenience function can be used from the module's initialization
- function. The string \var{value} must be null-terminated. Returns
- \code{-1} on error, \code{0} on success.
- \versionadded{2.0}
-\end{cfuncdesc}
-
-
-\subsection{Iterator Objects \label{iterator-objects}}
-
-Python provides two general-purpose iterator objects. The first, a
-sequence iterator, works with an arbitrary sequence supporting the
-\method{__getitem__()} method. The second works with a callable
-object and a sentinel value, calling the callable for each item in the
-sequence, and ending the iteration when the sentinel value is
-returned.
-
-\begin{cvardesc}{PyTypeObject}{PySeqIter_Type}
- Type object for iterator objects returned by
- \cfunction{PySeqIter_New()} and the one-argument form of the
- \function{iter()} built-in function for built-in sequence types.
- \versionadded{2.2}
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PySeqIter_Check}{op}
- Return true if the type of \var{op} is \cdata{PySeqIter_Type}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PySeqIter_New}{PyObject *seq}
- Return an iterator that works with a general sequence object,
- \var{seq}. The iteration ends when the sequence raises
- \exception{IndexError} for the subscripting operation.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cvardesc}{PyTypeObject}{PyCallIter_Type}
- Type object for iterator objects returned by
- \cfunction{PyCallIter_New()} and the two-argument form of the
- \function{iter()} built-in function.
- \versionadded{2.2}
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyCallIter_Check}{op}
- Return true if the type of \var{op} is \cdata{PyCallIter_Type}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyCallIter_New}{PyObject *callable,
- PyObject *sentinel}
- Return a new iterator. The first parameter, \var{callable}, can be
- any Python callable object that can be called with no parameters;
- each call to it should return the next item in the iteration. When
- \var{callable} returns a value equal to \var{sentinel}, the
- iteration will be terminated.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-
-\subsection{Descriptor Objects \label{descriptor-objects}}
-
-``Descriptors'' are objects that describe some attribute of an object.
-They are found in the dictionary of type objects.
-
-\begin{cvardesc}{PyTypeObject}{PyProperty_Type}
- The type object for the built-in descriptor types.
- \versionadded{2.2}
-\end{cvardesc}
-
-\begin{cfuncdesc}{PyObject*}{PyDescr_NewGetSet}{PyTypeObject *type,
- PyGetSetDef *getset}
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyDescr_NewMember}{PyTypeObject *type,
- PyMemberDef *meth}
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyDescr_NewMethod}{PyTypeObject *type,
- PyMethodDef *meth}
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyDescr_NewWrapper}{PyTypeObject *type,
- struct wrapperbase *wrapper,
- void *wrapped}
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyDescr_IsData}{PyObject *descr}
- Returns true if the descriptor objects \var{descr} describes a data
- attribute, or false if it describes a method. \var{descr} must be a
- descriptor object; there is no error checking.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyWrapper_New}{PyObject *, PyObject *}
- \versionadded{2.2}
-\end{cfuncdesc}
-
-
-\subsection{Slice Objects \label{slice-objects}}
-
-\begin{cvardesc}{PyTypeObject}{PySlice_Type}
- The type object for slice objects. This is the same as
- \code{types.SliceType}.
- \withsubitem{(in module types)}{\ttindex{SliceType}}
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PySlice_Check}{PyObject *ob}
- Returns true if \var{ob} is a slice object; \var{ob} must not be
- \NULL.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PySlice_New}{PyObject *start, PyObject *stop,
- PyObject *step}
- Return a new slice object with the given values. The \var{start},
- \var{stop}, and \var{step} parameters are used as the values of the
- slice object attributes of the same names. Any of the values may be
- \NULL, in which case the \code{None} will be used for the
- corresponding attribute. Returns \NULL{} if the new object could
- not be allocated.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PySlice_GetIndices}{PySliceObject *slice, int length,
- int *start, int *stop, int *step}
-Retrieve the start, stop and step indices from the slice object
-\var{slice}, assuming a sequence of length \var{length}. Treats
-indices greater than \var{length} as errors.
-
-Returns 0 on success and -1 on error with no exception set (unless one
-of the indices was not \constant{None} and failed to be converted to
-an integer, in which case -1 is returned with an exception set).
-
-You probably do not want to use this function. If you want to use
-slice objects in versions of Python prior to 2.3, you would probably
-do well to incorporate the source of \cfunction{PySlice_GetIndicesEx},
-suitably renamed, in the source of your extension.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PySlice_GetIndicesEx}{PySliceObject *slice, int length,
- int *start, int *stop, int *step,
- int *slicelength}
-Usable replacement for \cfunction{PySlice_GetIndices}. Retrieve the
-start, stop, and step indices from the slice object \var{slice}
-assuming a sequence of length \var{length}, and store the length of
-the slice in \var{slicelength}. Out of bounds indices are clipped in
-a manner consistent with the handling of normal slices.
-
-Returns 0 on success and -1 on error with exception set.
-
-\versionadded{2.3}
-\end{cfuncdesc}
-
-
-\subsection{Weak Reference Objects \label{weakref-objects}}
-
-Python supports \emph{weak references} as first-class objects. There
-are two specific object types which directly implement weak
-references. The first is a simple reference object, and the second
-acts as a proxy for the original object as much as it can.
-
-\begin{cfuncdesc}{int}{PyWeakref_Check}{ob}
- Return true if \var{ob} is either a reference or proxy object.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyWeakref_CheckRef}{ob}
- Return true if \var{ob} is a reference object.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyWeakref_CheckProxy}{ob}
- Return true if \var{ob} is a proxy object.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyWeakref_NewRef}{PyObject *ob,
- PyObject *callback}
- Return a weak reference object for the object \var{ob}. This will
- always return a new reference, but is not guaranteed to create a new
- object; an existing reference object may be returned. The second
- parameter, \var{callback}, can be a callable object that receives
- notification when \var{ob} is garbage collected; it should accept a
- single paramter, which will be the weak reference object itself.
- \var{callback} may also be \code{None} or \NULL. If \var{ob}
- is not a weakly-referencable object, or if \var{callback} is not
- callable, \code{None}, or \NULL, this will return \NULL{} and
- raise \exception{TypeError}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyWeakref_NewProxy}{PyObject *ob,
- PyObject *callback}
- Return a weak reference proxy object for the object \var{ob}. This
- will always return a new reference, but is not guaranteed to create
- a new object; an existing proxy object may be returned. The second
- parameter, \var{callback}, can be a callable object that receives
- notification when \var{ob} is garbage collected; it should accept a
- single paramter, which will be the weak reference object itself.
- \var{callback} may also be \code{None} or \NULL. If \var{ob} is not
- a weakly-referencable object, or if \var{callback} is not callable,
- \code{None}, or \NULL, this will return \NULL{} and raise
- \exception{TypeError}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyWeakref_GetObject}{PyObject *ref}
- Returns the referenced object from a weak reference, \var{ref}. If
- the referent is no longer live, returns \code{None}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyWeakref_GET_OBJECT}{PyObject *ref}
- Similar to \cfunction{PyWeakref_GetObject()}, but implemented as a
- macro that does no error checking.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-
-\subsection{CObjects \label{cObjects}}
-
-\obindex{CObject}
-Refer to \emph{Extending and Embedding the Python Interpreter},
-section~1.12, ``Providing a C API for an Extension Module,'' for more
-information on using these objects.
-
-
-\begin{ctypedesc}{PyCObject}
- This subtype of \ctype{PyObject} represents an opaque value, useful
- for C extension modules who need to pass an opaque value (as a
- \ctype{void*} pointer) through Python code to other C code. It is
- often used to make a C function pointer defined in one module
- available to other modules, so the regular import mechanism can be
- used to access C APIs defined in dynamically loaded modules.
-\end{ctypedesc}
-
-\begin{cfuncdesc}{int}{PyCObject_Check}{PyObject *p}
- Returns true if its argument is a \ctype{PyCObject}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtr}{void* cobj,
- void (*destr)(void *)}
- Creates a \ctype{PyCObject} from the \code{void *}\var{cobj}. The
- \var{destr} function will be called when the object is reclaimed,
- unless it is \NULL.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyCObject_FromVoidPtrAndDesc}{void* cobj,
- void* desc, void (*destr)(void *, void *)}
- Creates a \ctype{PyCObject} from the \ctype{void *}\var{cobj}. The
- \var{destr} function will be called when the object is reclaimed.
- The \var{desc} argument can be used to pass extra callback data for
- the destructor function.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void*}{PyCObject_AsVoidPtr}{PyObject* self}
- Returns the object \ctype{void *} that the \ctype{PyCObject}
- \var{self} was created with.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void*}{PyCObject_GetDesc}{PyObject* self}
- Returns the description \ctype{void *} that the \ctype{PyCObject}
- \var{self} was created with.
-\end{cfuncdesc}
-
-
-\subsection{Cell Objects \label{cell-objects}}
-
-``Cell'' objects are used to implement variables referenced by
-multiple scopes. For each such variable, a cell object is created to
-store the value; the local variables of each stack frame that
-references the value contains a reference to the cells from outer
-scopes which also use that variable. When the value is accessed, the
-value contained in the cell is used instead of the cell object
-itself. This de-referencing of the cell object requires support from
-the generated byte-code; these are not automatically de-referenced
-when accessed. Cell objects are not likely to be useful elsewhere.
-
-\begin{ctypedesc}{PyCellObject}
- The C structure used for cell objects.
-\end{ctypedesc}
-
-\begin{cvardesc}{PyTypeObject}{PyCell_Type}
- The type object corresponding to cell objects
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyCell_Check}{ob}
- Return true if \var{ob} is a cell object; \var{ob} must not be
- \NULL.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyCell_New}{PyObject *ob}
- Create and return a new cell object containing the value \var{ob}.
- The parameter may be \NULL.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyCell_Get}{PyObject *cell}
- Return the contents of the cell \var{cell}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyCell_GET}{PyObject *cell}
- Return the contents of the cell \var{cell}, but without checking
- that \var{cell} is non-\NULL{} and a call object.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyCell_Set}{PyObject *cell, PyObject *value}
- Set the contents of the cell object \var{cell} to \var{value}. This
- releases the reference to any current content of the cell.
- \var{value} may be \NULL. \var{cell} must be non-\NULL; if it is
- not a cell object, \code{-1} will be returned. On success, \code{0}
- will be returned.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyCell_SET}{PyObject *cell, PyObject *value}
- Sets the value of the cell object \var{cell} to \var{value}. No
- reference counts are adjusted, and no checks are made for safety;
- \var{cell} must be non-\NULL{} and must be a cell object.
-\end{cfuncdesc}
diff --git a/Doc/api/exceptions.tex b/Doc/api/exceptions.tex
deleted file mode 100644
index 8cd0fe4ffb..0000000000
--- a/Doc/api/exceptions.tex
+++ /dev/null
@@ -1,400 +0,0 @@
-\chapter{Exception Handling \label{exceptionHandling}}
-
-The functions described in this chapter will let you handle and raise Python
-exceptions. It is important to understand some of the basics of
-Python exception handling. It works somewhat like the
-\UNIX{} \cdata{errno} variable: there is a global indicator (per
-thread) of the last error that occurred. Most functions don't clear
-this on success, but will set it to indicate the cause of the error on
-failure. Most functions also return an error indicator, usually
-\NULL{} if they are supposed to return a pointer, or \code{-1} if they
-return an integer (exception: the \cfunction{PyArg_*()} functions
-return \code{1} for success and \code{0} for failure).
-
-When a function must fail because some function it called failed, it
-generally doesn't set the error indicator; the function it called
-already set it. It is responsible for either handling the error and
-clearing the exception or returning after cleaning up any resources it
-holds (such as object references or memory allocations); it should
-\emph{not} continue normally if it is not prepared to handle the
-error. If returning due to an error, it is important to indicate to
-the caller that an error has been set. If the error is not handled or
-carefully propagated, additional calls into the Python/C API may not
-behave as intended and may fail in mysterious ways.
-
-The error indicator consists of three Python objects corresponding to
-\withsubitem{(in module sys)}{
- \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
-the Python variables \code{sys.exc_type}, \code{sys.exc_value} and
-\code{sys.exc_traceback}. API functions exist to interact with the
-error indicator in various ways. There is a separate error indicator
-for each thread.
-
-% XXX Order of these should be more thoughtful.
-% Either alphabetical or some kind of structure.
-
-\begin{cfuncdesc}{void}{PyErr_Print}{}
- Print a standard traceback to \code{sys.stderr} and clear the error
- indicator. Call this function only when the error indicator is
- set. (Otherwise it will cause a fatal error!)
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyErr_Occurred}{}
- Test whether the error indicator is set. If set, return the
- exception \emph{type} (the first argument to the last call to one of
- the \cfunction{PyErr_Set*()} functions or to
- \cfunction{PyErr_Restore()}). If not set, return \NULL. You do
- not own a reference to the return value, so you do not need to
- \cfunction{Py_DECREF()} it. \note{Do not compare the return value
- to a specific exception; use \cfunction{PyErr_ExceptionMatches()}
- instead, shown below. (The comparison could easily fail since the
- exception may be an instance instead of a class, in the case of a
- class exception, or it may the a subclass of the expected
- exception.)}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyErr_ExceptionMatches}{PyObject *exc}
- Equivalent to \samp{PyErr_GivenExceptionMatches(PyErr_Occurred(),
- \var{exc})}. This should only be called when an exception is
- actually set; a memory access violation will occur if no exception
- has been raised.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyErr_GivenExceptionMatches}{PyObject *given, PyObject *exc}
- Return true if the \var{given} exception matches the exception in
- \var{exc}. If \var{exc} is a class object, this also returns true
- when \var{given} is an instance of a subclass. If \var{exc} is a
- tuple, all exceptions in the tuple (and recursively in subtuples)
- are searched for a match. If \var{given} is \NULL, a memory access
- violation will occur.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyErr_NormalizeException}{PyObject**exc, PyObject**val, PyObject**tb}
- Under certain circumstances, the values returned by
- \cfunction{PyErr_Fetch()} below can be ``unnormalized'', meaning
- that \code{*\var{exc}} is a class object but \code{*\var{val}} is
- not an instance of the same class. This function can be used to
- instantiate the class in that case. If the values are already
- normalized, nothing happens. The delayed normalization is
- implemented to improve performance.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyErr_Clear}{}
- Clear the error indicator. If the error indicator is not set, there
- is no effect.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyErr_Fetch}{PyObject **ptype, PyObject **pvalue,
- PyObject **ptraceback}
- Retrieve the error indicator into three variables whose addresses
- are passed. If the error indicator is not set, set all three
- variables to \NULL. If it is set, it will be cleared and you own a
- reference to each object retrieved. The value and traceback object
- may be \NULL{} even when the type object is not. \note{This
- function is normally only used by code that needs to handle
- exceptions or by code that needs to save and restore the error
- indicator temporarily.}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyErr_Restore}{PyObject *type, PyObject *value,
- PyObject *traceback}
- Set the error indicator from the three objects. If the error
- indicator is already set, it is cleared first. If the objects are
- \NULL, the error indicator is cleared. Do not pass a \NULL{} type
- and non-\NULL{} value or traceback. The exception type should be a
- class. Do not pass an invalid exception type or value.
- (Violating these rules will cause subtle problems later.) This call
- takes away a reference to each object: you must own a reference to
- each object before the call and after the call you no longer own
- these references. (If you don't understand this, don't use this
- function. I warned you.) \note{This function is normally only used
- by code that needs to save and restore the error indicator
- temporarily; use \cfunction{PyErr_Fetch()} to save the current
- exception state.}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyErr_SetString}{PyObject *type, char *message}
- This is the most common way to set the error indicator. The first
- argument specifies the exception type; it is normally one of the
- standard exceptions, e.g. \cdata{PyExc_RuntimeError}. You need not
- increment its reference count. The second argument is an error
- message; it is converted to a string object.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyErr_SetObject}{PyObject *type, PyObject *value}
- This function is similar to \cfunction{PyErr_SetString()} but lets
- you specify an arbitrary Python object for the ``value'' of the
- exception.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyErr_Format}{PyObject *exception,
- const char *format, \moreargs}
- This function sets the error indicator and returns \NULL.
- \var{exception} should be a Python exception (class, not
- an instance). \var{format} should be a string, containing format
- codes, similar to \cfunction{printf()}. The \code{width.precision}
- before a format code is parsed, but the width part is ignored.
-
- \begin{tableii}{c|l}{character}{Character}{Meaning}
- \lineii{c}{Character, as an \ctype{int} parameter}
- \lineii{d}{Number in decimal, as an \ctype{int} parameter}
- \lineii{x}{Number in hexadecimal, as an \ctype{int} parameter}
- \lineii{s}{A string, as a \ctype{char *} parameter}
- \lineii{p}{A hex pointer, as a \ctype{void *} parameter}
- \end{tableii}
-
- An unrecognized format character causes all the rest of the format
- string to be copied as-is to the result string, and any extra
- arguments discarded.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyErr_SetNone}{PyObject *type}
- This is a shorthand for \samp{PyErr_SetObject(\var{type},
- Py_None)}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyErr_BadArgument}{}
- This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
- \var{message})}, where \var{message} indicates that a built-in
- operation was invoked with an illegal argument. It is mostly for
- internal use.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyErr_NoMemory}{}
- This is a shorthand for \samp{PyErr_SetNone(PyExc_MemoryError)}; it
- returns \NULL{} so an object allocation function can write
- \samp{return PyErr_NoMemory();} when it runs out of memory.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrno}{PyObject *type}
- This is a convenience function to raise an exception when a C
- library function has returned an error and set the C variable
- \cdata{errno}. It constructs a tuple object whose first item is the
- integer \cdata{errno} value and whose second item is the
- corresponding error message (gotten from
- \cfunction{strerror()}\ttindex{strerror()}), and then calls
- \samp{PyErr_SetObject(\var{type}, \var{object})}. On \UNIX, when
- the \cdata{errno} value is \constant{EINTR}, indicating an
- interrupted system call, this calls
- \cfunction{PyErr_CheckSignals()}, and if that set the error
- indicator, leaves it set to that. The function always returns
- \NULL, so a wrapper function around a system call can write
- \samp{return PyErr_SetFromErrno(\var{type});} when the system call
- returns an error.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrnoWithFilename}{PyObject *type,
- char *filename}
- Similar to \cfunction{PyErr_SetFromErrno()}, with the additional
- behavior that if \var{filename} is not \NULL, it is passed to the
- constructor of \var{type} as a third parameter. In the case of
- exceptions such as \exception{IOError} and \exception{OSError}, this
- is used to define the \member{filename} attribute of the exception
- instance.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyErr_SetFromWindowsErr}{int ierr}
- This is a convenience function to raise \exception{WindowsError}.
- If called with \var{ierr} of \cdata{0}, the error code returned by a
- call to \cfunction{GetLastError()} is used instead. It calls the
- Win32 function \cfunction{FormatMessage()} to retrieve the Windows
- description of error code given by \var{ierr} or
- \cfunction{GetLastError()}, then it constructs a tuple object whose
- first item is the \var{ierr} value and whose second item is the
- corresponding error message (gotten from
- \cfunction{FormatMessage()}), and then calls
- \samp{PyErr_SetObject(\var{PyExc_WindowsError}, \var{object})}.
- This function always returns \NULL.
- Availability: Windows.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyErr_SetExcFromWindowsErr}{PyObject *type,
- int ierr}
- Similar to \cfunction{PyErr_SetFromWindowsErr()}, with an additional
- parameter specifying the exception type to be raised.
- Availability: Windows.
- \versionadded{2.3}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyErr_SetFromWindowsErrWithFilename}{int ierr,
- char *filename}
- Similar to \cfunction{PyErr_SetFromWindowsErr()}, with the
- additional behavior that if \var{filename} is not \NULL, it is
- passed to the constructor of \exception{WindowsError} as a third
- parameter.
- Availability: Windows.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyErr_SetExcFromWindowsErrWithFilename}
- {PyObject *type, int ierr, char *filename}
- Similar to \cfunction{PyErr_SetFromWindowsErrWithFilename()}, with
- an additional parameter specifying the exception type to be raised.
- Availability: Windows.
- \versionadded{2.3}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyErr_BadInternalCall}{}
- This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError,
- \var{message})}, where \var{message} indicates that an internal
- operation (e.g. a Python/C API function) was invoked with an illegal
- argument. It is mostly for internal use.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyErr_Warn}{PyObject *category, char *message}
- Issue a warning message. The \var{category} argument is a warning
- category (see below) or \NULL; the \var{message} argument is a
- message string.
-
- This function normally prints a warning message to \var{sys.stderr};
- however, it is also possible that the user has specified that
- warnings are to be turned into errors, and in that case this will
- raise an exception. It is also possible that the function raises an
- exception because of a problem with the warning machinery (the
- implementation imports the \module{warnings} module to do the heavy
- lifting). The return value is \code{0} if no exception is raised,
- or \code{-1} if an exception is raised. (It is not possible to
- determine whether a warning message is actually printed, nor what
- the reason is for the exception; this is intentional.) If an
- exception is raised, the caller should do its normal exception
- handling (for example, \cfunction{Py_DECREF()} owned references and
- return an error value).
-
- Warning categories must be subclasses of \cdata{Warning}; the
- default warning category is \cdata{RuntimeWarning}. The standard
- Python warning categories are available as global variables whose
- names are \samp{PyExc_} followed by the Python exception name.
- These have the type \ctype{PyObject*}; they are all class objects.
- Their names are \cdata{PyExc_Warning}, \cdata{PyExc_UserWarning},
- \cdata{PyExc_DeprecationWarning}, \cdata{PyExc_SyntaxWarning},
- \cdata{PyExc_RuntimeWarning}, and \cdata{PyExc_FutureWarning}.
- \cdata{PyExc_Warning} is a subclass of \cdata{PyExc_Exception}; the
- other warning categories are subclasses of \cdata{PyExc_Warning}.
-
- For information about warning control, see the documentation for the
- \module{warnings} module and the \programopt{-W} option in the
- command line documentation. There is no C API for warning control.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyErr_WarnExplicit}{PyObject *category, char *message,
- char *filename, int lineno, char *module, PyObject *registry}
- Issue a warning message with explicit control over all warning
- attributes. This is a straightforward wrapper around the Python
- function \function{warnings.warn_explicit()}, see there for more
- information. The \var{module} and \var{registry} arguments may be
- set to \NULL{} to get the default effect described there.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyErr_CheckSignals}{}
- This function interacts with Python's signal handling. It checks
- whether a signal has been sent to the processes and if so, invokes
- the corresponding signal handler. If the
- \module{signal}\refbimodindex{signal} module is supported, this can
- invoke a signal handler written in Python. In all cases, the
- default effect for \constant{SIGINT}\ttindex{SIGINT} is to raise the
- \withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
- \exception{KeyboardInterrupt} exception. If an exception is raised
- the error indicator is set and the function returns \code{1};
- otherwise the function returns \code{0}. The error indicator may or
- may not be cleared if it was previously set.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyErr_SetInterrupt}{}
- This function is obsolete. It simulates the effect of a
- \constant{SIGINT}\ttindex{SIGINT} signal arriving --- the next time
- \cfunction{PyErr_CheckSignals()} is called,
- \withsubitem{(built-in exception)}{\ttindex{KeyboardInterrupt}}
- \exception{KeyboardInterrupt} will be raised. It may be called
- without holding the interpreter lock.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyErr_NewException}{char *name,
- PyObject *base,
- PyObject *dict}
- This utility function creates and returns a new exception object.
- The \var{name} argument must be the name of the new exception, a C
- string of the form \code{module.class}. The \var{base} and
- \var{dict} arguments are normally \NULL. This creates a class
- object derived from the root for all exceptions, the built-in name
- \exception{Exception} (accessible in C as \cdata{PyExc_Exception}).
- The \member{__module__} attribute of the new class is set to the
- first part (up to the last dot) of the \var{name} argument, and the
- class name is set to the last part (after the last dot). The
- \var{base} argument can be used to specify an alternate base class.
- The \var{dict} argument can be used to specify a dictionary of class
- variables and methods.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyErr_WriteUnraisable}{PyObject *obj}
- This utility function prints a warning message to \code{sys.stderr}
- when an exception has been set but it is impossible for the
- interpreter to actually raise the exception. It is used, for
- example, when an exception occurs in an \method{__del__()} method.
-
- The function is called with a single argument \var{obj} that
- identifies where the context in which the unraisable exception
- occurred. The repr of \var{obj} will be printed in the warning
- message.
-\end{cfuncdesc}
-
-\section{Standard Exceptions \label{standardExceptions}}
-
-All standard Python exceptions are available as global variables whose
-names are \samp{PyExc_} followed by the Python exception name. These
-have the type \ctype{PyObject*}; they are all class objects. For
-completeness, here are all the variables:
-
-\begin{tableiii}{l|l|c}{cdata}{C Name}{Python Name}{Notes}
- \lineiii{PyExc_Exception}{\exception{Exception}}{(1)}
- \lineiii{PyExc_StandardError}{\exception{StandardError}}{(1)}
- \lineiii{PyExc_ArithmeticError}{\exception{ArithmeticError}}{(1)}
- \lineiii{PyExc_LookupError}{\exception{LookupError}}{(1)}
- \lineiii{PyExc_AssertionError}{\exception{AssertionError}}{}
- \lineiii{PyExc_AttributeError}{\exception{AttributeError}}{}
- \lineiii{PyExc_EOFError}{\exception{EOFError}}{}
- \lineiii{PyExc_EnvironmentError}{\exception{EnvironmentError}}{(1)}
- \lineiii{PyExc_FloatingPointError}{\exception{FloatingPointError}}{}
- \lineiii{PyExc_IOError}{\exception{IOError}}{}
- \lineiii{PyExc_ImportError}{\exception{ImportError}}{}
- \lineiii{PyExc_IndexError}{\exception{IndexError}}{}
- \lineiii{PyExc_KeyError}{\exception{KeyError}}{}
- \lineiii{PyExc_KeyboardInterrupt}{\exception{KeyboardInterrupt}}{}
- \lineiii{PyExc_MemoryError}{\exception{MemoryError}}{}
- \lineiii{PyExc_NameError}{\exception{NameError}}{}
- \lineiii{PyExc_NotImplementedError}{\exception{NotImplementedError}}{}
- \lineiii{PyExc_OSError}{\exception{OSError}}{}
- \lineiii{PyExc_OverflowError}{\exception{OverflowError}}{}
- \lineiii{PyExc_ReferenceError}{\exception{ReferenceError}}{(2)}
- \lineiii{PyExc_RuntimeError}{\exception{RuntimeError}}{}
- \lineiii{PyExc_SyntaxError}{\exception{SyntaxError}}{}
- \lineiii{PyExc_SystemError}{\exception{SystemError}}{}
- \lineiii{PyExc_SystemExit}{\exception{SystemExit}}{}
- \lineiii{PyExc_TypeError}{\exception{TypeError}}{}
- \lineiii{PyExc_ValueError}{\exception{ValueError}}{}
- \lineiii{PyExc_WindowsError}{\exception{WindowsError}}{(3)}
- \lineiii{PyExc_ZeroDivisionError}{\exception{ZeroDivisionError}}{}
-\end{tableiii}
-
-\noindent
-Notes:
-\begin{description}
-\item[(1)]
- This is a base class for other standard exceptions.
-
-\item[(2)]
- This is the same as \exception{weakref.ReferenceError}.
-
-\item[(3)]
- Only defined on Windows; protect code that uses this by testing that
- the preprocessor macro \code{MS_WINDOWS} is defined.
-\end{description}
-
-
-\section{Deprecation of String Exceptions}
-
-All exceptions built into Python or provided in the standard library
-are derived from \exception{Exception}.
-\withsubitem{(built-in exception)}{\ttindex{Exception}}
-
-String exceptions are still supported in the interpreter to allow
-existing code to run unmodified, but this will also change in a future
-release.
diff --git a/Doc/api/init.tex b/Doc/api/init.tex
deleted file mode 100644
index 388f479457..0000000000
--- a/Doc/api/init.tex
+++ /dev/null
@@ -1,804 +0,0 @@
-\chapter{Initialization, Finalization, and Threads
- \label{initialization}}
-
-\begin{cfuncdesc}{void}{Py_Initialize}{}
- Initialize the Python interpreter. In an application embedding
- Python, this should be called before using any other Python/C API
- functions; with the exception of
- \cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()},
- \cfunction{PyEval_InitThreads()}\ttindex{PyEval_InitThreads()},
- \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()},
- and \cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()}.
- This initializes the table of loaded modules (\code{sys.modules}),
- and\withsubitem{(in module sys)}{\ttindex{modules}\ttindex{path}}
- creates the fundamental modules
- \module{__builtin__}\refbimodindex{__builtin__},
- \module{__main__}\refbimodindex{__main__} and
- \module{sys}\refbimodindex{sys}. It also initializes the module
- search\indexiii{module}{search}{path} path (\code{sys.path}).
- It does not set \code{sys.argv}; use
- \cfunction{PySys_SetArgv()}\ttindex{PySys_SetArgv()} for that. This
- is a no-op when called for a second time (without calling
- \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} first). There is
- no return value; it is a fatal error if the initialization fails.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_IsInitialized}{}
- Return true (nonzero) when the Python interpreter has been
- initialized, false (zero) if not. After \cfunction{Py_Finalize()}
- is called, this returns false until \cfunction{Py_Initialize()} is
- called again.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{Py_Finalize}{}
- Undo all initializations made by \cfunction{Py_Initialize()} and
- subsequent use of Python/C API functions, and destroy all
- sub-interpreters (see \cfunction{Py_NewInterpreter()} below) that
- were created and not yet destroyed since the last call to
- \cfunction{Py_Initialize()}. Ideally, this frees all memory
- allocated by the Python interpreter. This is a no-op when called
- for a second time (without calling \cfunction{Py_Initialize()} again
- first). There is no return value; errors during finalization are
- ignored.
-
- This function is provided for a number of reasons. An embedding
- application might want to restart Python without having to restart
- the application itself. An application that has loaded the Python
- interpreter from a dynamically loadable library (or DLL) might want
- to free all memory allocated by Python before unloading the
- DLL. During a hunt for memory leaks in an application a developer
- might want to free all memory allocated by Python before exiting
- from the application.
-
- \strong{Bugs and caveats:} The destruction of modules and objects in
- modules is done in random order; this may cause destructors
- (\method{__del__()} methods) to fail when they depend on other
- objects (even functions) or modules. Dynamically loaded extension
- modules loaded by Python are not unloaded. Small amounts of memory
- allocated by the Python interpreter may not be freed (if you find a
- leak, please report it). Memory tied up in circular references
- between objects is not freed. Some memory allocated by extension
- modules may not be freed. Some extensions may not work properly if
- their initialization routine is called more than once; this can
- happen if an application calls \cfunction{Py_Initialize()} and
- \cfunction{Py_Finalize()} more than once.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyThreadState*}{Py_NewInterpreter}{}
- Create a new sub-interpreter. This is an (almost) totally separate
- environment for the execution of Python code. In particular, the
- new interpreter has separate, independent versions of all imported
- modules, including the fundamental modules
- \module{__builtin__}\refbimodindex{__builtin__},
- \module{__main__}\refbimodindex{__main__} and
- \module{sys}\refbimodindex{sys}. The table of loaded modules
- (\code{sys.modules}) and the module search path (\code{sys.path})
- are also separate. The new environment has no \code{sys.argv}
- variable. It has new standard I/O stream file objects
- \code{sys.stdin}, \code{sys.stdout} and \code{sys.stderr} (however
- these refer to the same underlying \ctype{FILE} structures in the C
- library).
- \withsubitem{(in module sys)}{
- \ttindex{stdout}\ttindex{stderr}\ttindex{stdin}}
-
- The return value points to the first thread state created in the new
- sub-interpreter. This thread state is made the current thread
- state. Note that no actual thread is created; see the discussion of
- thread states below. If creation of the new interpreter is
- unsuccessful, \NULL{} is returned; no exception is set since the
- exception state is stored in the current thread state and there may
- not be a current thread state. (Like all other Python/C API
- functions, the global interpreter lock must be held before calling
- this function and is still held when it returns; however, unlike
- most other Python/C API functions, there needn't be a current thread
- state on entry.)
-
- Extension modules are shared between (sub-)interpreters as follows:
- the first time a particular extension is imported, it is initialized
- normally, and a (shallow) copy of its module's dictionary is
- squirreled away. When the same extension is imported by another
- (sub-)interpreter, a new module is initialized and filled with the
- contents of this copy; the extension's \code{init} function is not
- called. Note that this is different from what happens when an
- extension is imported after the interpreter has been completely
- re-initialized by calling
- \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and
- \cfunction{Py_Initialize()}\ttindex{Py_Initialize()}; in that case,
- the extension's \code{init\var{module}} function \emph{is} called
- again.
-
- \strong{Bugs and caveats:} Because sub-interpreters (and the main
- interpreter) are part of the same process, the insulation between
- them isn't perfect --- for example, using low-level file operations
- like \withsubitem{(in module os)}{\ttindex{close()}}
- \function{os.close()} they can (accidentally or maliciously) affect
- each other's open files. Because of the way extensions are shared
- between (sub-)interpreters, some extensions may not work properly;
- this is especially likely when the extension makes use of (static)
- global variables, or when the extension manipulates its module's
- dictionary after its initialization. It is possible to insert
- objects created in one sub-interpreter into a namespace of another
- sub-interpreter; this should be done with great care to avoid
- sharing user-defined functions, methods, instances or classes
- between sub-interpreters, since import operations executed by such
- objects may affect the wrong (sub-)interpreter's dictionary of
- loaded modules. (XXX This is a hard-to-fix bug that will be
- addressed in a future release.)
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{Py_EndInterpreter}{PyThreadState *tstate}
- Destroy the (sub-)interpreter represented by the given thread state.
- The given thread state must be the current thread state. See the
- discussion of thread states below. When the call returns, the
- current thread state is \NULL. All thread states associated with
- this interpreted are destroyed. (The global interpreter lock must
- be held before calling this function and is still held when it
- returns.) \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} will
- destroy all sub-interpreters that haven't been explicitly destroyed
- at that point.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{Py_SetProgramName}{char *name}
- This function should be called before
- \cfunction{Py_Initialize()}\ttindex{Py_Initialize()} is called
- for the first time, if it is called at all. It tells the
- interpreter the value of the \code{argv[0]} argument to the
- \cfunction{main()}\ttindex{main()} function of the program. This is
- used by \cfunction{Py_GetPath()}\ttindex{Py_GetPath()} and some
- other functions below to find the Python run-time libraries relative
- to the interpreter executable. The default value is
- \code{'python'}. The argument should point to a zero-terminated
- character string in static storage whose contents will not change
- for the duration of the program's execution. No code in the Python
- interpreter will change the contents of this storage.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{char*}{Py_GetProgramName}{}
- Return the program name set with
- \cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()}, or the
- default. The returned string points into static storage; the caller
- should not modify its value.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{char*}{Py_GetPrefix}{}
- Return the \emph{prefix} for installed platform-independent files.
- This is derived through a number of complicated rules from the
- program name set with \cfunction{Py_SetProgramName()} and some
- environment variables; for example, if the program name is
- \code{'/usr/local/bin/python'}, the prefix is \code{'/usr/local'}.
- The returned string points into static storage; the caller should
- not modify its value. This corresponds to the \makevar{prefix}
- variable in the top-level \file{Makefile} and the
- \longprogramopt{prefix} argument to the \program{configure} script
- at build time. The value is available to Python code as
- \code{sys.prefix}. It is only useful on \UNIX. See also the next
- function.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{char*}{Py_GetExecPrefix}{}
- Return the \emph{exec-prefix} for installed
- platform-\emph{de}pendent files. This is derived through a number
- of complicated rules from the program name set with
- \cfunction{Py_SetProgramName()} and some environment variables; for
- example, if the program name is \code{'/usr/local/bin/python'}, the
- exec-prefix is \code{'/usr/local'}. The returned string points into
- static storage; the caller should not modify its value. This
- corresponds to the \makevar{exec_prefix} variable in the top-level
- \file{Makefile} and the \longprogramopt{exec-prefix} argument to the
- \program{configure} script at build time. The value is available
- to Python code as \code{sys.exec_prefix}. It is only useful on
- \UNIX.
-
- Background: The exec-prefix differs from the prefix when platform
- dependent files (such as executables and shared libraries) are
- installed in a different directory tree. In a typical installation,
- platform dependent files may be installed in the
- \file{/usr/local/plat} subtree while platform independent may be
- installed in \file{/usr/local}.
-
- Generally speaking, a platform is a combination of hardware and
- software families, e.g. Sparc machines running the Solaris 2.x
- operating system are considered the same platform, but Intel
- machines running Solaris 2.x are another platform, and Intel
- machines running Linux are yet another platform. Different major
- revisions of the same operating system generally also form different
- platforms. Non-\UNIX{} operating systems are a different story; the
- installation strategies on those systems are so different that the
- prefix and exec-prefix are meaningless, and set to the empty string.
- Note that compiled Python bytecode files are platform independent
- (but not independent from the Python version by which they were
- compiled!).
-
- System administrators will know how to configure the \program{mount}
- or \program{automount} programs to share \file{/usr/local} between
- platforms while having \file{/usr/local/plat} be a different
- filesystem for each platform.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{char*}{Py_GetProgramFullPath}{}
- Return the full program name of the Python executable; this is
- computed as a side-effect of deriving the default module search path
- from the program name (set by
- \cfunction{Py_SetProgramName()}\ttindex{Py_SetProgramName()} above).
- The returned string points into static storage; the caller should
- not modify its value. The value is available to Python code as
- \code{sys.executable}.
- \withsubitem{(in module sys)}{\ttindex{executable}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{char*}{Py_GetPath}{}
- \indexiii{module}{search}{path}
- Return the default module search path; this is computed from the
- program name (set by \cfunction{Py_SetProgramName()} above) and some
- environment variables. The returned string consists of a series of
- directory names separated by a platform dependent delimiter
- character. The delimiter character is \character{:} on \UNIX,
- \character{;} on Windows, and \character{\e n} (the \ASCII{}
- newline character) on Macintosh. The returned string points into
- static storage; the caller should not modify its value. The value
- is available to Python code as the list
- \code{sys.path}\withsubitem{(in module sys)}{\ttindex{path}}, which
- may be modified to change the future search path for loaded
- modules.
-
- % XXX should give the exact rules
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{const char*}{Py_GetVersion}{}
- Return the version of this Python interpreter. This is a string
- that looks something like
-
-\begin{verbatim}
-"1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"
-\end{verbatim}
-
- The first word (up to the first space character) is the current
- Python version; the first three characters are the major and minor
- version separated by a period. The returned string points into
- static storage; the caller should not modify its value. The value
- is available to Python code as \code{sys.version}.
- \withsubitem{(in module sys)}{\ttindex{version}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{const char*}{Py_GetPlatform}{}
- Return the platform identifier for the current platform. On \UNIX,
- this is formed from the ``official'' name of the operating system,
- converted to lower case, followed by the major revision number;
- e.g., for Solaris 2.x, which is also known as SunOS 5.x, the value
- is \code{'sunos5'}. On Macintosh, it is \code{'mac'}. On Windows,
- it is \code{'win'}. The returned string points into static storage;
- the caller should not modify its value. The value is available to
- Python code as \code{sys.platform}.
- \withsubitem{(in module sys)}{\ttindex{platform}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{const char*}{Py_GetCopyright}{}
- Return the official copyright string for the current Python version,
- for example
-
- \code{'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'}
-
- The returned string points into static storage; the caller should
- not modify its value. The value is available to Python code as
- \code{sys.copyright}.
- \withsubitem{(in module sys)}{\ttindex{copyright}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{const char*}{Py_GetCompiler}{}
- Return an indication of the compiler used to build the current
- Python version, in square brackets, for example:
-
-\begin{verbatim}
-"[GCC 2.7.2.2]"
-\end{verbatim}
-
- The returned string points into static storage; the caller should
- not modify its value. The value is available to Python code as part
- of the variable \code{sys.version}.
- \withsubitem{(in module sys)}{\ttindex{version}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{const char*}{Py_GetBuildInfo}{}
- Return information about the sequence number and build date and time
- of the current Python interpreter instance, for example
-
-\begin{verbatim}
-"#67, Aug 1 1997, 22:34:28"
-\end{verbatim}
-
- The returned string points into static storage; the caller should
- not modify its value. The value is available to Python code as part
- of the variable \code{sys.version}.
- \withsubitem{(in module sys)}{\ttindex{version}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PySys_SetArgv}{int argc, char **argv}
- Set \code{sys.argv} based on \var{argc} and \var{argv}. These
- parameters are similar to those passed to the program's
- \cfunction{main()}\ttindex{main()} function with the difference that
- the first entry should refer to the script file to be executed
- rather than the executable hosting the Python interpreter. If there
- isn't a script that will be run, the first entry in \var{argv} can
- be an empty string. If this function fails to initialize
- \code{sys.argv}, a fatal condition is signalled using
- \cfunction{Py_FatalError()}\ttindex{Py_FatalError()}.
- \withsubitem{(in module sys)}{\ttindex{argv}}
- % XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
- % check w/ Guido.
-\end{cfuncdesc}
-
-% XXX Other PySys thingies (doesn't really belong in this chapter)
-
-\section{Thread State and the Global Interpreter Lock
- \label{threads}}
-
-\index{global interpreter lock}
-\index{interpreter lock}
-\index{lock, interpreter}
-
-The Python interpreter is not fully thread safe. In order to support
-multi-threaded Python programs, there's a global lock that must be
-held by the current thread before it can safely access Python objects.
-Without the lock, even the simplest operations could cause problems in
-a multi-threaded program: for example, when two threads simultaneously
-increment the reference count of the same object, the reference count
-could end up being incremented only once instead of twice.
-
-Therefore, the rule exists that only the thread that has acquired the
-global interpreter lock may operate on Python objects or call Python/C
-API functions. In order to support multi-threaded Python programs,
-the interpreter regularly releases and reacquires the lock --- by
-default, every ten bytecode instructions (this can be changed with
-\withsubitem{(in module sys)}{\ttindex{setcheckinterval()}}
-\function{sys.setcheckinterval()}). The lock is also released and
-reacquired around potentially blocking I/O operations like reading or
-writing a file, so that other threads can run while the thread that
-requests the I/O is waiting for the I/O operation to complete.
-
-The Python interpreter needs to keep some bookkeeping information
-separate per thread --- for this it uses a data structure called
-\ctype{PyThreadState}\ttindex{PyThreadState}. This is new in Python
-1.5; in earlier versions, such state was stored in global variables,
-and switching threads could cause problems. In particular, exception
-handling is now thread safe, when the application uses
-\withsubitem{(in module sys)}{\ttindex{exc_info()}}
-\function{sys.exc_info()} to access the exception last raised in the
-current thread.
-
-There's one global variable left, however: the pointer to the current
-\ctype{PyThreadState}\ttindex{PyThreadState} structure. While most
-thread packages have a way to store ``per-thread global data,''
-Python's internal platform independent thread abstraction doesn't
-support this yet. Therefore, the current thread state must be
-manipulated explicitly.
-
-This is easy enough in most cases. Most code manipulating the global
-interpreter lock has the following simple structure:
-
-\begin{verbatim}
-Save the thread state in a local variable.
-Release the interpreter lock.
-...Do some blocking I/O operation...
-Reacquire the interpreter lock.
-Restore the thread state from the local variable.
-\end{verbatim}
-
-This is so common that a pair of macros exists to simplify it:
-
-\begin{verbatim}
-Py_BEGIN_ALLOW_THREADS
-...Do some blocking I/O operation...
-Py_END_ALLOW_THREADS
-\end{verbatim}
-
-The
-\csimplemacro{Py_BEGIN_ALLOW_THREADS}\ttindex{Py_BEGIN_ALLOW_THREADS}
-macro opens a new block and declares a hidden local variable; the
-\csimplemacro{Py_END_ALLOW_THREADS}\ttindex{Py_END_ALLOW_THREADS}
-macro closes the block. Another advantage of using these two macros
-is that when Python is compiled without thread support, they are
-defined empty, thus saving the thread state and lock manipulations.
-
-When thread support is enabled, the block above expands to the
-following code:
-
-\begin{verbatim}
- PyThreadState *_save;
-
- _save = PyEval_SaveThread();
- ...Do some blocking I/O operation...
- PyEval_RestoreThread(_save);
-\end{verbatim}
-
-Using even lower level primitives, we can get roughly the same effect
-as follows:
-
-\begin{verbatim}
- PyThreadState *_save;
-
- _save = PyThreadState_Swap(NULL);
- PyEval_ReleaseLock();
- ...Do some blocking I/O operation...
- PyEval_AcquireLock();
- PyThreadState_Swap(_save);
-\end{verbatim}
-
-There are some subtle differences; in particular,
-\cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()} saves
-and restores the value of the global variable
-\cdata{errno}\ttindex{errno}, since the lock manipulation does not
-guarantee that \cdata{errno} is left alone. Also, when thread support
-is disabled,
-\cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} and
-\cfunction{PyEval_RestoreThread()} don't manipulate the lock; in this
-case, \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} and
-\cfunction{PyEval_AcquireLock()}\ttindex{PyEval_AcquireLock()} are not
-available. This is done so that dynamically loaded extensions
-compiled with thread support enabled can be loaded by an interpreter
-that was compiled with disabled thread support.
-
-The global interpreter lock is used to protect the pointer to the
-current thread state. When releasing the lock and saving the thread
-state, the current thread state pointer must be retrieved before the
-lock is released (since another thread could immediately acquire the
-lock and store its own thread state in the global variable).
-Conversely, when acquiring the lock and restoring the thread state,
-the lock must be acquired before storing the thread state pointer.
-
-Why am I going on with so much detail about this? Because when
-threads are created from C, they don't have the global interpreter
-lock, nor is there a thread state data structure for them. Such
-threads must bootstrap themselves into existence, by first creating a
-thread state data structure, then acquiring the lock, and finally
-storing their thread state pointer, before they can start using the
-Python/C API. When they are done, they should reset the thread state
-pointer, release the lock, and finally free their thread state data
-structure.
-
-When creating a thread data structure, you need to provide an
-interpreter state data structure. The interpreter state data
-structure hold global data that is shared by all threads in an
-interpreter, for example the module administration
-(\code{sys.modules}). Depending on your needs, you can either create
-a new interpreter state data structure, or share the interpreter state
-data structure used by the Python main thread (to access the latter,
-you must obtain the thread state and access its \member{interp} member;
-this must be done by a thread that is created by Python or by the main
-thread after Python is initialized).
-
-Assuming you have access to an interpreter object, the typical idiom
-for calling into Python from a C thread is
-
-\begin{verbatim}
- PyThreadState *tstate;
- PyObject *result;
-
- /* interp is your reference to an interpreter object. */
- tstate = PyThreadState_New(interp);
- PyEval_AcquireThread(tstate);
-
- /* Perform Python actions here. */
- result = CallSomeFunction();
- /* evaluate result */
-
- /* Release the thread. No Python API allowed beyond this point. */
- PyEval_ReleaseThread(tstate);
-
- /* You can either delete the thread state, or save it
- until you need it the next time. */
- PyThreadState_Delete(tstate);
-\end{verbatim}
-
-\begin{ctypedesc}{PyInterpreterState}
- This data structure represents the state shared by a number of
- cooperating threads. Threads belonging to the same interpreter
- share their module administration and a few other internal items.
- There are no public members in this structure.
-
- Threads belonging to different interpreters initially share nothing,
- except process state like available memory, open file descriptors
- and such. The global interpreter lock is also shared by all
- threads, regardless of to which interpreter they belong.
-\end{ctypedesc}
-
-\begin{ctypedesc}{PyThreadState}
- This data structure represents the state of a single thread. The
- only public data member is \ctype{PyInterpreterState
- *}\member{interp}, which points to this thread's interpreter state.
-\end{ctypedesc}
-
-\begin{cfuncdesc}{void}{PyEval_InitThreads}{}
- Initialize and acquire the global interpreter lock. It should be
- called in the main thread before creating a second thread or
- engaging in any other thread operations such as
- \cfunction{PyEval_ReleaseLock()}\ttindex{PyEval_ReleaseLock()} or
- \code{PyEval_ReleaseThread(\var{tstate})}\ttindex{PyEval_ReleaseThread()}.
- It is not needed before calling
- \cfunction{PyEval_SaveThread()}\ttindex{PyEval_SaveThread()} or
- \cfunction{PyEval_RestoreThread()}\ttindex{PyEval_RestoreThread()}.
-
- This is a no-op when called for a second time. It is safe to call
- this function before calling
- \cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
-
- When only the main thread exists, no lock operations are needed.
- This is a common situation (most Python programs do not use
- threads), and the lock operations slow the interpreter down a bit.
- Therefore, the lock is not created initially. This situation is
- equivalent to having acquired the lock: when there is only a single
- thread, all object accesses are safe. Therefore, when this function
- initializes the lock, it also acquires it. Before the Python
- \module{thread}\refbimodindex{thread} module creates a new thread,
- knowing that either it has the lock or the lock hasn't been created
- yet, it calls \cfunction{PyEval_InitThreads()}. When this call
- returns, it is guaranteed that the lock has been created and that it
- has acquired it.
-
- It is \strong{not} safe to call this function when it is unknown
- which thread (if any) currently has the global interpreter lock.
-
- This function is not available when thread support is disabled at
- compile time.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyEval_AcquireLock}{}
- Acquire the global interpreter lock. The lock must have been
- created earlier. If this thread already has the lock, a deadlock
- ensues. This function is not available when thread support is
- disabled at compile time.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyEval_ReleaseLock}{}
- Release the global interpreter lock. The lock must have been
- created earlier. This function is not available when thread support
- is disabled at compile time.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyEval_AcquireThread}{PyThreadState *tstate}
- Acquire the global interpreter lock and then set the current thread
- state to \var{tstate}, which should not be \NULL. The lock must
- have been created earlier. If this thread already has the lock,
- deadlock ensues. This function is not available when thread support
- is disabled at compile time.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyEval_ReleaseThread}{PyThreadState *tstate}
- Reset the current thread state to \NULL{} and release the global
- interpreter lock. The lock must have been created earlier and must
- be held by the current thread. The \var{tstate} argument, which
- must not be \NULL, is only used to check that it represents the
- current thread state --- if it isn't, a fatal error is reported.
- This function is not available when thread support is disabled at
- compile time.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyThreadState*}{PyEval_SaveThread}{}
- Release the interpreter lock (if it has been created and thread
- support is enabled) and reset the thread state to \NULL, returning
- the previous thread state (which is not \NULL). If the lock has
- been created, the current thread must have acquired it. (This
- function is available even when thread support is disabled at
- compile time.)
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyEval_RestoreThread}{PyThreadState *tstate}
- Acquire the interpreter lock (if it has been created and thread
- support is enabled) and set the thread state to \var{tstate}, which
- must not be \NULL. If the lock has been created, the current thread
- must not have acquired it, otherwise deadlock ensues. (This
- function is available even when thread support is disabled at
- compile time.)
-\end{cfuncdesc}
-
-The following macros are normally used without a trailing semicolon;
-look for example usage in the Python source distribution.
-
-\begin{csimplemacrodesc}{Py_BEGIN_ALLOW_THREADS}
- This macro expands to
- \samp{\{ PyThreadState *_save; _save = PyEval_SaveThread();}.
- Note that it contains an opening brace; it must be matched with a
- following \csimplemacro{Py_END_ALLOW_THREADS} macro. See above for
- further discussion of this macro. It is a no-op when thread support
- is disabled at compile time.
-\end{csimplemacrodesc}
-
-\begin{csimplemacrodesc}{Py_END_ALLOW_THREADS}
- This macro expands to \samp{PyEval_RestoreThread(_save); \}}.
- Note that it contains a closing brace; it must be matched with an
- earlier \csimplemacro{Py_BEGIN_ALLOW_THREADS} macro. See above for
- further discussion of this macro. It is a no-op when thread support
- is disabled at compile time.
-\end{csimplemacrodesc}
-
-\begin{csimplemacrodesc}{Py_BLOCK_THREADS}
- This macro expands to \samp{PyEval_RestoreThread(_save);}: it is
- equivalent to \csimplemacro{Py_END_ALLOW_THREADS} without the
- closing brace. It is a no-op when thread support is disabled at
- compile time.
-\end{csimplemacrodesc}
-
-\begin{csimplemacrodesc}{Py_UNBLOCK_THREADS}
- This macro expands to \samp{_save = PyEval_SaveThread();}: it is
- equivalent to \csimplemacro{Py_BEGIN_ALLOW_THREADS} without the
- opening brace and variable declaration. It is a no-op when thread
- support is disabled at compile time.
-\end{csimplemacrodesc}
-
-All of the following functions are only available when thread support
-is enabled at compile time, and must be called only when the
-interpreter lock has been created.
-
-\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_New}{}
- Create a new interpreter state object. The interpreter lock need
- not be held, but may be held if it is necessary to serialize calls
- to this function.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyInterpreterState_Clear}{PyInterpreterState *interp}
- Reset all information in an interpreter state object. The
- interpreter lock must be held.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyInterpreterState_Delete}{PyInterpreterState *interp}
- Destroy an interpreter state object. The interpreter lock need not
- be held. The interpreter state must have been reset with a previous
- call to \cfunction{PyInterpreterState_Clear()}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyThreadState*}{PyThreadState_New}{PyInterpreterState *interp}
- Create a new thread state object belonging to the given interpreter
- object. The interpreter lock need not be held, but may be held if
- it is necessary to serialize calls to this function.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyThreadState_Clear}{PyThreadState *tstate}
- Reset all information in a thread state object. The interpreter lock
- must be held.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyThreadState_Delete}{PyThreadState *tstate}
- Destroy a thread state object. The interpreter lock need not be
- held. The thread state must have been reset with a previous call to
- \cfunction{PyThreadState_Clear()}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Get}{}
- Return the current thread state. The interpreter lock must be
- held. When the current thread state is \NULL, this issues a fatal
- error (so that the caller needn't check for \NULL).
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Swap}{PyThreadState *tstate}
- Swap the current thread state with the thread state given by the
- argument \var{tstate}, which may be \NULL. The interpreter lock
- must be held.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyThreadState_GetDict}{}
- Return a dictionary in which extensions can store thread-specific
- state information. Each extension should use a unique key to use to
- store state in the dictionary. It is okay to call this function
- when no current thread state is available.
- If this function returns \NULL, no exception has been raised and the
- caller should assume no current thread state is available.
- \versionchanged[Previously this could only be called when a current
- thread is active, and \NULL meant that an exception was raised]{2.3}
-\end{cfuncdesc}
-
-
-\section{Profiling and Tracing \label{profiling}}
-
-\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
-
-The Python interpreter provides some low-level support for attaching
-profiling and execution tracing facilities. These are used for
-profiling, debugging, and coverage analysis tools.
-
-Starting with Python 2.2, the implementation of this facility was
-substantially revised, and an interface from C was added. This C
-interface allows the profiling or tracing code to avoid the overhead
-of calling through Python-level callable objects, making a direct C
-function call instead. The essential attributes of the facility have
-not changed; the interface allows trace functions to be installed
-per-thread, and the basic events reported to the trace function are
-the same as had been reported to the Python-level trace functions in
-previous versions.
-
-\begin{ctypedesc}[Py_tracefunc]{int (*Py_tracefunc)(PyObject *obj,
- PyFrameObject *frame, int what,
- PyObject *arg)}
- The type of the trace function registered using
- \cfunction{PyEval_SetProfile()} and \cfunction{PyEval_SetTrace()}.
- The first parameter is the object passed to the registration
- function as \var{obj}, \var{frame} is the frame object to which the
- event pertains, \var{what} is one of the constants
- \constant{PyTrace_CALL}, \constant{PyTrace_EXCEPT},
- \constant{PyTrace_LINE} or \constant{PyTrace_RETURN}, and \var{arg}
- depends on the value of \var{what}:
-
- \begin{tableii}{l|l}{constant}{Value of \var{what}}{Meaning of \var{arg}}
- \lineii{PyTrace_CALL}{Always \NULL.}
- \lineii{PyTrace_EXCEPT}{Exception information as returned by
- \function{sys.exc_info()}.}
- \lineii{PyTrace_LINE}{Always \NULL.}
- \lineii{PyTrace_RETURN}{Value being returned to the caller.}
- \end{tableii}
-\end{ctypedesc}
-
-\begin{cvardesc}{int}{PyTrace_CALL}
- The value of the \var{what} parameter to a \ctype{Py_tracefunc}
- function when a new call to a function or method is being reported,
- or a new entry into a generator. Note that the creation of the
- iterator for a generator function is not reported as there is no
- control transfer to the Python bytecode in the corresponding frame.
-\end{cvardesc}
-
-\begin{cvardesc}{int}{PyTrace_EXCEPT}
- The value of the \var{what} parameter to a \ctype{Py_tracefunc}
- function when an exception has been raised. The callback function
- is called with this value for \var{what} when after any bytecode is
- processed after which the exception becomes set within the frame
- being executed. The effect of this is that as exception propogation
- causes the Python stack to unwind, the callback is called upon
- return to each frame as the exception propagates. Only trace
- functions receives these events; they are not needed by the
- profiler.
-\end{cvardesc}
-
-\begin{cvardesc}{int}{PyTrace_LINE}
- The value passed as the \var{what} parameter to a trace function
- (but not a profiling function) when a line-number event is being
- reported.
-\end{cvardesc}
-
-\begin{cvardesc}{int}{PyTrace_RETURN}
- The value for the \var{what} parameter to \ctype{Py_tracefunc}
- functions when a call is returning without propogating an exception.
-\end{cvardesc}
-
-\begin{cfuncdesc}{void}{PyEval_SetProfile}{Py_tracefunc func, PyObject *obj}
- Set the profiler function to \var{func}. The \var{obj} parameter is
- passed to the function as its first parameter, and may be any Python
- object, or \NULL. If the profile function needs to maintain state,
- using a different value for \var{obj} for each thread provides a
- convenient and thread-safe place to store it. The profile function
- is called for all monitored events except the line-number events.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyEval_SetTrace}{Py_tracefunc func, PyObject *obj}
- Set the the tracing function to \var{func}. This is similar to
- \cfunction{PyEval_SetProfile()}, except the tracing function does
- receive line-number events.
-\end{cfuncdesc}
-
-
-\section{Advanced Debugger Support \label{advanced-debugging}}
-\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
-
-These functions are only intended to be used by advanced debugging
-tools.
-
-\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_Head}{}
- Return the interpreter state object at the head of the list of all
- such objects.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyInterpreterState*}{PyInterpreterState_Next}{PyInterpreterState *interp}
- Return the next interpreter state object after \var{interp} from the
- list of all such objects.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyThreadState *}{PyInterpreterState_ThreadHead}{PyInterpreterState *interp}
- Return the a pointer to the first \ctype{PyThreadState} object in
- the list of threads associated with the interpreter \var{interp}.
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyThreadState*}{PyThreadState_Next}{PyThreadState *tstate}
- Return the next thread state object after \var{tstate} from the list
- of all such objects belonging to the same \ctype{PyInterpreterState}
- object.
- \versionadded{2.2}
-\end{cfuncdesc}
diff --git a/Doc/api/intro.tex b/Doc/api/intro.tex
deleted file mode 100644
index 65298eba78..0000000000
--- a/Doc/api/intro.tex
+++ /dev/null
@@ -1,562 +0,0 @@
-\chapter{Introduction \label{intro}}
-
-
-The Application Programmer's Interface to Python gives C and
-\Cpp{} programmers access to the Python interpreter at a variety of
-levels. The API is equally usable from \Cpp, but for brevity it is
-generally referred to as the Python/C API. There are two
-fundamentally different reasons for using the Python/C API. The first
-reason is to write \emph{extension modules} for specific purposes;
-these are C modules that extend the Python interpreter. This is
-probably the most common use. The second reason is to use Python as a
-component in a larger application; this technique is generally
-referred to as \dfn{embedding} Python in an application.
-
-Writing an extension module is a relatively well-understood process,
-where a ``cookbook'' approach works well. There are several tools
-that automate the process to some extent. While people have embedded
-Python in other applications since its early existence, the process of
-embedding Python is less straightforward than writing an extension.
-
-Many API functions are useful independent of whether you're embedding
-or extending Python; moreover, most applications that embed Python
-will need to provide a custom extension as well, so it's probably a
-good idea to become familiar with writing an extension before
-attempting to embed Python in a real application.
-
-
-\section{Include Files \label{includes}}
-
-All function, type and macro definitions needed to use the Python/C
-API are included in your code by the following line:
-
-\begin{verbatim}
-#include "Python.h"
-\end{verbatim}
-
-This implies inclusion of the following standard headers:
-\code{}, \code{}, \code{},
-\code{}, and \code{} (if available).
-Since Python may define some pre-processor definitions which affect
-the standard headers on some systems, you must include \file{Python.h}
-before any standard headers are included.
-
-All user visible names defined by Python.h (except those defined by
-the included standard headers) have one of the prefixes \samp{Py} or
-\samp{_Py}. Names beginning with \samp{_Py} are for internal use by
-the Python implementation and should not be used by extension writers.
-Structure member names do not have a reserved prefix.
-
-\strong{Important:} user code should never define names that begin
-with \samp{Py} or \samp{_Py}. This confuses the reader, and
-jeopardizes the portability of the user code to future Python
-versions, which may define additional names beginning with one of
-these prefixes.
-
-The header files are typically installed with Python. On \UNIX, these
-are located in the directories
-\file{\envvar{prefix}/include/python\var{version}/} and
-\file{\envvar{exec_prefix}/include/python\var{version}/}, where
-\envvar{prefix} and \envvar{exec_prefix} are defined by the
-corresponding parameters to Python's \program{configure} script and
-\var{version} is \code{sys.version[:3]}. On Windows, the headers are
-installed in \file{\envvar{prefix}/include}, where \envvar{prefix} is
-the installation directory specified to the installer.
-
-To include the headers, place both directories (if different) on your
-compiler's search path for includes. Do \emph{not} place the parent
-directories on the search path and then use
-\samp{\#include }; this will break on
-multi-platform builds since the platform independent headers under
-\envvar{prefix} include the platform specific headers from
-\envvar{exec_prefix}.
-
-\Cpp{} users should note that though the API is defined entirely using
-C, the header files do properly declare the entry points to be
-\code{extern "C"}, so there is no need to do anything special to use
-the API from \Cpp.
-
-
-\section{Objects, Types and Reference Counts \label{objects}}
-
-Most Python/C API functions have one or more arguments as well as a
-return value of type \ctype{PyObject*}. This type is a pointer
-to an opaque data type representing an arbitrary Python
-object. Since all Python object types are treated the same way by the
-Python language in most situations (e.g., assignments, scope rules,
-and argument passing), it is only fitting that they should be
-represented by a single C type. Almost all Python objects live on the
-heap: you never declare an automatic or static variable of type
-\ctype{PyObject}, only pointer variables of type \ctype{PyObject*} can
-be declared. The sole exception are the type objects\obindex{type};
-since these must never be deallocated, they are typically static
-\ctype{PyTypeObject} objects.
-
-All Python objects (even Python integers) have a \dfn{type} and a
-\dfn{reference count}. An object's type determines what kind of object
-it is (e.g., an integer, a list, or a user-defined function; there are
-many more as explained in the \citetitle[../ref/ref.html]{Python
-Reference Manual}). For each of the well-known types there is a macro
-to check whether an object is of that type; for instance,
-\samp{PyList_Check(\var{a})} is true if (and only if) the object
-pointed to by \var{a} is a Python list.
-
-
-\subsection{Reference Counts \label{refcounts}}
-
-The reference count is important because today's computers have a
-finite (and often severely limited) memory size; it counts how many
-different places there are that have a reference to an object. Such a
-place could be another object, or a global (or static) C variable, or
-a local variable in some C function. When an object's reference count
-becomes zero, the object is deallocated. If it contains references to
-other objects, their reference count is decremented. Those other
-objects may be deallocated in turn, if this decrement makes their
-reference count become zero, and so on. (There's an obvious problem
-with objects that reference each other here; for now, the solution is
-``don't do that.'')
-
-Reference counts are always manipulated explicitly. The normal way is
-to use the macro \cfunction{Py_INCREF()}\ttindex{Py_INCREF()} to
-increment an object's reference count by one, and
-\cfunction{Py_DECREF()}\ttindex{Py_DECREF()} to decrement it by
-one. The \cfunction{Py_DECREF()} macro is considerably more complex
-than the incref one, since it must check whether the reference count
-becomes zero and then cause the object's deallocator to be called.
-The deallocator is a function pointer contained in the object's type
-structure. The type-specific deallocator takes care of decrementing
-the reference counts for other objects contained in the object if this
-is a compound object type, such as a list, as well as performing any
-additional finalization that's needed. There's no chance that the
-reference count can overflow; at least as many bits are used to hold
-the reference count as there are distinct memory locations in virtual
-memory (assuming \code{sizeof(long) >= sizeof(char*)}). Thus, the
-reference count increment is a simple operation.
-
-It is not necessary to increment an object's reference count for every
-local variable that contains a pointer to an object. In theory, the
-object's reference count goes up by one when the variable is made to
-point to it and it goes down by one when the variable goes out of
-scope. However, these two cancel each other out, so at the end the
-reference count hasn't changed. The only real reason to use the
-reference count is to prevent the object from being deallocated as
-long as our variable is pointing to it. If we know that there is at
-least one other reference to the object that lives at least as long as
-our variable, there is no need to increment the reference count
-temporarily. An important situation where this arises is in objects
-that are passed as arguments to C functions in an extension module
-that are called from Python; the call mechanism guarantees to hold a
-reference to every argument for the duration of the call.
-
-However, a common pitfall is to extract an object from a list and
-hold on to it for a while without incrementing its reference count.
-Some other operation might conceivably remove the object from the
-list, decrementing its reference count and possible deallocating it.
-The real danger is that innocent-looking operations may invoke
-arbitrary Python code which could do this; there is a code path which
-allows control to flow back to the user from a \cfunction{Py_DECREF()},
-so almost any operation is potentially dangerous.
-
-A safe approach is to always use the generic operations (functions
-whose name begins with \samp{PyObject_}, \samp{PyNumber_},
-\samp{PySequence_} or \samp{PyMapping_}). These operations always
-increment the reference count of the object they return. This leaves
-the caller with the responsibility to call
-\cfunction{Py_DECREF()} when they are done with the result; this soon
-becomes second nature.
-
-
-\subsubsection{Reference Count Details \label{refcountDetails}}
-
-The reference count behavior of functions in the Python/C API is best
-explained in terms of \emph{ownership of references}. Note that we
-talk of owning references, never of owning objects; objects are always
-shared! When a function owns a reference, it has to dispose of it
-properly --- either by passing ownership on (usually to its caller) or
-by calling \cfunction{Py_DECREF()} or \cfunction{Py_XDECREF()}. When
-a function passes ownership of a reference on to its caller, the
-caller is said to receive a \emph{new} reference. When no ownership
-is transferred, the caller is said to \emph{borrow} the reference.
-Nothing needs to be done for a borrowed reference.
-
-Conversely, when a calling function passes it a reference to an
-object, there are two possibilities: the function \emph{steals} a
-reference to the object, or it does not. Few functions steal
-references; the two notable exceptions are
-\cfunction{PyList_SetItem()}\ttindex{PyList_SetItem()} and
-\cfunction{PyTuple_SetItem()}\ttindex{PyTuple_SetItem()}, which
-steal a reference to the item (but not to the tuple or list into which
-the item is put!). These functions were designed to steal a reference
-because of a common idiom for populating a tuple or list with newly
-created objects; for example, the code to create the tuple \code{(1,
-2, "three")} could look like this (forgetting about error handling for
-the moment; a better way to code this is shown below):
-
-\begin{verbatim}
-PyObject *t;
-
-t = PyTuple_New(3);
-PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
-PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
-PyTuple_SetItem(t, 2, PyString_FromString("three"));
-\end{verbatim}
-
-Incidentally, \cfunction{PyTuple_SetItem()} is the \emph{only} way to
-set tuple items; \cfunction{PySequence_SetItem()} and
-\cfunction{PyObject_SetItem()} refuse to do this since tuples are an
-immutable data type. You should only use
-\cfunction{PyTuple_SetItem()} for tuples that you are creating
-yourself.
-
-Equivalent code for populating a list can be written using
-\cfunction{PyList_New()} and \cfunction{PyList_SetItem()}. Such code
-can also use \cfunction{PySequence_SetItem()}; this illustrates the
-difference between the two (the extra \cfunction{Py_DECREF()} calls):
-
-\begin{verbatim}
-PyObject *l, *x;
-
-l = PyList_New(3);
-x = PyInt_FromLong(1L);
-PySequence_SetItem(l, 0, x); Py_DECREF(x);
-x = PyInt_FromLong(2L);
-PySequence_SetItem(l, 1, x); Py_DECREF(x);
-x = PyString_FromString("three");
-PySequence_SetItem(l, 2, x); Py_DECREF(x);
-\end{verbatim}
-
-You might find it strange that the ``recommended'' approach takes more
-code. However, in practice, you will rarely use these ways of
-creating and populating a tuple or list. There's a generic function,
-\cfunction{Py_BuildValue()}, that can create most common objects from
-C values, directed by a \dfn{format string}. For example, the
-above two blocks of code could be replaced by the following (which
-also takes care of the error checking):
-
-\begin{verbatim}
-PyObject *t, *l;
-
-t = Py_BuildValue("(iis)", 1, 2, "three");
-l = Py_BuildValue("[iis]", 1, 2, "three");
-\end{verbatim}
-
-It is much more common to use \cfunction{PyObject_SetItem()} and
-friends with items whose references you are only borrowing, like
-arguments that were passed in to the function you are writing. In
-that case, their behaviour regarding reference counts is much saner,
-since you don't have to increment a reference count so you can give a
-reference away (``have it be stolen''). For example, this function
-sets all items of a list (actually, any mutable sequence) to a given
-item:
-
-\begin{verbatim}
-int
-set_all(PyObject *target, PyObject *item)
-{
- int i, n;
-
- n = PyObject_Length(target);
- if (n < 0)
- return -1;
- for (i = 0; i < n; i++) {
- if (PyObject_SetItem(target, i, item) < 0)
- return -1;
- }
- return 0;
-}
-\end{verbatim}
-\ttindex{set_all()}
-
-The situation is slightly different for function return values.
-While passing a reference to most functions does not change your
-ownership responsibilities for that reference, many functions that
-return a referece to an object give you ownership of the reference.
-The reason is simple: in many cases, the returned object is created
-on the fly, and the reference you get is the only reference to the
-object. Therefore, the generic functions that return object
-references, like \cfunction{PyObject_GetItem()} and
-\cfunction{PySequence_GetItem()}, always return a new reference (the
-caller becomes the owner of the reference).
-
-It is important to realize that whether you own a reference returned
-by a function depends on which function you call only --- \emph{the
-plumage} (the type of the type of the object passed as an
-argument to the function) \emph{doesn't enter into it!} Thus, if you
-extract an item from a list using \cfunction{PyList_GetItem()}, you
-don't own the reference --- but if you obtain the same item from the
-same list using \cfunction{PySequence_GetItem()} (which happens to
-take exactly the same arguments), you do own a reference to the
-returned object.
-
-Here is an example of how you could write a function that computes the
-sum of the items in a list of integers; once using
-\cfunction{PyList_GetItem()}\ttindex{PyList_GetItem()}, and once using
-\cfunction{PySequence_GetItem()}\ttindex{PySequence_GetItem()}.
-
-\begin{verbatim}
-long
-sum_list(PyObject *list)
-{
- int i, n;
- long total = 0;
- PyObject *item;
-
- n = PyList_Size(list);
- if (n < 0)
- return -1; /* Not a list */
- for (i = 0; i < n; i++) {
- item = PyList_GetItem(list, i); /* Can't fail */
- if (!PyInt_Check(item)) continue; /* Skip non-integers */
- total += PyInt_AsLong(item);
- }
- return total;
-}
-\end{verbatim}
-\ttindex{sum_list()}
-
-\begin{verbatim}
-long
-sum_sequence(PyObject *sequence)
-{
- int i, n;
- long total = 0;
- PyObject *item;
- n = PySequence_Length(sequence);
- if (n < 0)
- return -1; /* Has no length */
- for (i = 0; i < n; i++) {
- item = PySequence_GetItem(sequence, i);
- if (item == NULL)
- return -1; /* Not a sequence, or other failure */
- if (PyInt_Check(item))
- total += PyInt_AsLong(item);
- Py_DECREF(item); /* Discard reference ownership */
- }
- return total;
-}
-\end{verbatim}
-\ttindex{sum_sequence()}
-
-
-\subsection{Types \label{types}}
-
-There are few other data types that play a significant role in
-the Python/C API; most are simple C types such as \ctype{int},
-\ctype{long}, \ctype{double} and \ctype{char*}. A few structure types
-are used to describe static tables used to list the functions exported
-by a module or the data attributes of a new object type, and another
-is used to describe the value of a complex number. These will
-be discussed together with the functions that use them.
-
-
-\section{Exceptions \label{exceptions}}
-
-The Python programmer only needs to deal with exceptions if specific
-error handling is required; unhandled exceptions are automatically
-propagated to the caller, then to the caller's caller, and so on, until
-they reach the top-level interpreter, where they are reported to the
-user accompanied by a stack traceback.
-
-For C programmers, however, error checking always has to be explicit.
-All functions in the Python/C API can raise exceptions, unless an
-explicit claim is made otherwise in a function's documentation. In
-general, when a function encounters an error, it sets an exception,
-discards any object references that it owns, and returns an
-error indicator --- usually \NULL{} or \code{-1}. A few functions
-return a Boolean true/false result, with false indicating an error.
-Very few functions return no explicit error indicator or have an
-ambiguous return value, and require explicit testing for errors with
-\cfunction{PyErr_Occurred()}\ttindex{PyErr_Occurred()}.
-
-Exception state is maintained in per-thread storage (this is
-equivalent to using global storage in an unthreaded application). A
-thread can be in one of two states: an exception has occurred, or not.
-The function \cfunction{PyErr_Occurred()} can be used to check for
-this: it returns a borrowed reference to the exception type object
-when an exception has occurred, and \NULL{} otherwise. There are a
-number of functions to set the exception state:
-\cfunction{PyErr_SetString()}\ttindex{PyErr_SetString()} is the most
-common (though not the most general) function to set the exception
-state, and \cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} clears the
-exception state.
-
-The full exception state consists of three objects (all of which can
-be \NULL): the exception type, the corresponding exception
-value, and the traceback. These have the same meanings as the Python
-\withsubitem{(in module sys)}{
- \ttindex{exc_type}\ttindex{exc_value}\ttindex{exc_traceback}}
-objects \code{sys.exc_type}, \code{sys.exc_value}, and
-\code{sys.exc_traceback}; however, they are not the same: the Python
-objects represent the last exception being handled by a Python
-\keyword{try} \ldots\ \keyword{except} statement, while the C level
-exception state only exists while an exception is being passed on
-between C functions until it reaches the Python bytecode interpreter's
-main loop, which takes care of transferring it to \code{sys.exc_type}
-and friends.
-
-Note that starting with Python 1.5, the preferred, thread-safe way to
-access the exception state from Python code is to call the function
-\withsubitem{(in module sys)}{\ttindex{exc_info()}}
-\function{sys.exc_info()}, which returns the per-thread exception state
-for Python code. Also, the semantics of both ways to access the
-exception state have changed so that a function which catches an
-exception will save and restore its thread's exception state so as to
-preserve the exception state of its caller. This prevents common bugs
-in exception handling code caused by an innocent-looking function
-overwriting the exception being handled; it also reduces the often
-unwanted lifetime extension for objects that are referenced by the
-stack frames in the traceback.
-
-As a general principle, a function that calls another function to
-perform some task should check whether the called function raised an
-exception, and if so, pass the exception state on to its caller. It
-should discard any object references that it owns, and return an
-error indicator, but it should \emph{not} set another exception ---
-that would overwrite the exception that was just raised, and lose
-important information about the exact cause of the error.
-
-A simple example of detecting exceptions and passing them on is shown
-in the \cfunction{sum_sequence()}\ttindex{sum_sequence()} example
-above. It so happens that that example doesn't need to clean up any
-owned references when it detects an error. The following example
-function shows some error cleanup. First, to remind you why you like
-Python, we show the equivalent Python code:
-
-\begin{verbatim}
-def incr_item(dict, key):
- try:
- item = dict[key]
- except KeyError:
- item = 0
- dict[key] = item + 1
-\end{verbatim}
-\ttindex{incr_item()}
-
-Here is the corresponding C code, in all its glory:
-
-\begin{verbatim}
-int
-incr_item(PyObject *dict, PyObject *key)
-{
- /* Objects all initialized to NULL for Py_XDECREF */
- PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
- int rv = -1; /* Return value initialized to -1 (failure) */
-
- item = PyObject_GetItem(dict, key);
- if (item == NULL) {
- /* Handle KeyError only: */
- if (!PyErr_ExceptionMatches(PyExc_KeyError))
- goto error;
-
- /* Clear the error and use zero: */
- PyErr_Clear();
- item = PyInt_FromLong(0L);
- if (item == NULL)
- goto error;
- }
- const_one = PyInt_FromLong(1L);
- if (const_one == NULL)
- goto error;
-
- incremented_item = PyNumber_Add(item, const_one);
- if (incremented_item == NULL)
- goto error;
-
- if (PyObject_SetItem(dict, key, incremented_item) < 0)
- goto error;
- rv = 0; /* Success */
- /* Continue with cleanup code */
-
- error:
- /* Cleanup code, shared by success and failure path */
-
- /* Use Py_XDECREF() to ignore NULL references */
- Py_XDECREF(item);
- Py_XDECREF(const_one);
- Py_XDECREF(incremented_item);
-
- return rv; /* -1 for error, 0 for success */
-}
-\end{verbatim}
-\ttindex{incr_item()}
-
-This example represents an endorsed use of the \keyword{goto} statement
-in C! It illustrates the use of
-\cfunction{PyErr_ExceptionMatches()}\ttindex{PyErr_ExceptionMatches()} and
-\cfunction{PyErr_Clear()}\ttindex{PyErr_Clear()} to
-handle specific exceptions, and the use of
-\cfunction{Py_XDECREF()}\ttindex{Py_XDECREF()} to
-dispose of owned references that may be \NULL{} (note the
-\character{X} in the name; \cfunction{Py_DECREF()} would crash when
-confronted with a \NULL{} reference). It is important that the
-variables used to hold owned references are initialized to \NULL{} for
-this to work; likewise, the proposed return value is initialized to
-\code{-1} (failure) and only set to success after the final call made
-is successful.
-
-
-\section{Embedding Python \label{embedding}}
-
-The one important task that only embedders (as opposed to extension
-writers) of the Python interpreter have to worry about is the
-initialization, and possibly the finalization, of the Python
-interpreter. Most functionality of the interpreter can only be used
-after the interpreter has been initialized.
-
-The basic initialization function is
-\cfunction{Py_Initialize()}\ttindex{Py_Initialize()}.
-This initializes the table of loaded modules, and creates the
-fundamental modules \module{__builtin__}\refbimodindex{__builtin__},
-\module{__main__}\refbimodindex{__main__}, \module{sys}\refbimodindex{sys},
-and \module{exceptions}.\refbimodindex{exceptions} It also initializes
-the module search path (\code{sys.path}).%
-\indexiii{module}{search}{path}
-\withsubitem{(in module sys)}{\ttindex{path}}
-
-\cfunction{Py_Initialize()} does not set the ``script argument list''
-(\code{sys.argv}). If this variable is needed by Python code that
-will be executed later, it must be set explicitly with a call to
-\code{PySys_SetArgv(\var{argc},
-\var{argv})}\ttindex{PySys_SetArgv()} subsequent to the call to
-\cfunction{Py_Initialize()}.
-
-On most systems (in particular, on \UNIX{} and Windows, although the
-details are slightly different),
-\cfunction{Py_Initialize()} calculates the module search path based
-upon its best guess for the location of the standard Python
-interpreter executable, assuming that the Python library is found in a
-fixed location relative to the Python interpreter executable. In
-particular, it looks for a directory named
-\file{lib/python\shortversion} relative to the parent directory where
-the executable named \file{python} is found on the shell command
-search path (the environment variable \envvar{PATH}).
-
-For instance, if the Python executable is found in
-\file{/usr/local/bin/python}, it will assume that the libraries are in
-\file{/usr/local/lib/python\shortversion}. (In fact, this particular path
-is also the ``fallback'' location, used when no executable file named
-\file{python} is found along \envvar{PATH}.) The user can override
-this behavior by setting the environment variable \envvar{PYTHONHOME},
-or insert additional directories in front of the standard path by
-setting \envvar{PYTHONPATH}.
-
-The embedding application can steer the search by calling
-\code{Py_SetProgramName(\var{file})}\ttindex{Py_SetProgramName()} \emph{before} calling
-\cfunction{Py_Initialize()}. Note that \envvar{PYTHONHOME} still
-overrides this and \envvar{PYTHONPATH} is still inserted in front of
-the standard path. An application that requires total control has to
-provide its own implementation of
-\cfunction{Py_GetPath()}\ttindex{Py_GetPath()},
-\cfunction{Py_GetPrefix()}\ttindex{Py_GetPrefix()},
-\cfunction{Py_GetExecPrefix()}\ttindex{Py_GetExecPrefix()}, and
-\cfunction{Py_GetProgramFullPath()}\ttindex{Py_GetProgramFullPath()} (all
-defined in \file{Modules/getpath.c}).
-
-Sometimes, it is desirable to ``uninitialize'' Python. For instance,
-the application may want to start over (make another call to
-\cfunction{Py_Initialize()}) or the application is simply done with its
-use of Python and wants to free all memory allocated by Python. This
-can be accomplished by calling \cfunction{Py_Finalize()}. The function
-\cfunction{Py_IsInitialized()}\ttindex{Py_IsInitialized()} returns
-true if Python is currently in the initialized state. More
-information about these functions is given in a later chapter.
diff --git a/Doc/api/memory.tex b/Doc/api/memory.tex
deleted file mode 100644
index 3da6860ac9..0000000000
--- a/Doc/api/memory.tex
+++ /dev/null
@@ -1,203 +0,0 @@
-\chapter{Memory Management \label{memory}}
-\sectionauthor{Vladimir Marangozov}{Vladimir.Marangozov@inrialpes.fr}
-
-
-\section{Overview \label{memoryOverview}}
-
-Memory management in Python involves a private heap containing all
-Python objects and data structures. The management of this private
-heap is ensured internally by the \emph{Python memory manager}. The
-Python memory manager has different components which deal with various
-dynamic storage management aspects, like sharing, segmentation,
-preallocation or caching.
-
-At the lowest level, a raw memory allocator ensures that there is
-enough room in the private heap for storing all Python-related data
-by interacting with the memory manager of the operating system. On top
-of the raw memory allocator, several object-specific allocators
-operate on the same heap and implement distinct memory management
-policies adapted to the peculiarities of every object type. For
-example, integer objects are managed differently within the heap than
-strings, tuples or dictionaries because integers imply different
-storage requirements and speed/space tradeoffs. The Python memory
-manager thus delegates some of the work to the object-specific
-allocators, but ensures that the latter operate within the bounds of
-the private heap.
-
-It is important to understand that the management of the Python heap
-is performed by the interpreter itself and that the user has no
-control over it, even if she regularly manipulates object pointers to
-memory blocks inside that heap. The allocation of heap space for
-Python objects and other internal buffers is performed on demand by
-the Python memory manager through the Python/C API functions listed in
-this document.
-
-To avoid memory corruption, extension writers should never try to
-operate on Python objects with the functions exported by the C
-library: \cfunction{malloc()}\ttindex{malloc()},
-\cfunction{calloc()}\ttindex{calloc()},
-\cfunction{realloc()}\ttindex{realloc()} and
-\cfunction{free()}\ttindex{free()}. This will result in
-mixed calls between the C allocator and the Python memory manager
-with fatal consequences, because they implement different algorithms
-and operate on different heaps. However, one may safely allocate and
-release memory blocks with the C library allocator for individual
-purposes, as shown in the following example:
-
-\begin{verbatim}
- PyObject *res;
- char *buf = (char *) malloc(BUFSIZ); /* for I/O */
-
- if (buf == NULL)
- return PyErr_NoMemory();
- ...Do some I/O operation involving buf...
- res = PyString_FromString(buf);
- free(buf); /* malloc'ed */
- return res;
-\end{verbatim}
-
-In this example, the memory request for the I/O buffer is handled by
-the C library allocator. The Python memory manager is involved only
-in the allocation of the string object returned as a result.
-
-In most situations, however, it is recommended to allocate memory from
-the Python heap specifically because the latter is under control of
-the Python memory manager. For example, this is required when the
-interpreter is extended with new object types written in C. Another
-reason for using the Python heap is the desire to \emph{inform} the
-Python memory manager about the memory needs of the extension module.
-Even when the requested memory is used exclusively for internal,
-highly-specific purposes, delegating all memory requests to the Python
-memory manager causes the interpreter to have a more accurate image of
-its memory footprint as a whole. Consequently, under certain
-circumstances, the Python memory manager may or may not trigger
-appropriate actions, like garbage collection, memory compaction or
-other preventive procedures. Note that by using the C library
-allocator as shown in the previous example, the allocated memory for
-the I/O buffer escapes completely the Python memory manager.
-
-
-\section{Memory Interface \label{memoryInterface}}
-
-The following function sets, modeled after the ANSI C standard,
-but specifying behavior when requesting zero bytes,
-are available for allocating and releasing memory from the Python heap:
-
-
-\begin{cfuncdesc}{void*}{PyMem_Malloc}{size_t n}
- Allocates \var{n} bytes and returns a pointer of type \ctype{void*}
- to the allocated memory, or \NULL{} if the request fails.
- Requesting zero bytes returns a distinct non-\NULL{} pointer if
- possible, as if \cfunction{PyMem_Malloc(1)} had been called instead.
- The memory will not have been initialized in any way.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void*}{PyMem_Realloc}{void *p, size_t n}
- Resizes the memory block pointed to by \var{p} to \var{n} bytes.
- The contents will be unchanged to the minimum of the old and the new
- sizes. If \var{p} is \NULL, the call is equivalent to
- \cfunction{PyMem_Malloc(\var{n})}; else if \var{n} is equal to zero, the
- memory block is resized but is not freed, and the returned pointer
- is non-\NULL. Unless \var{p} is \NULL, it must have been
- returned by a previous call to \cfunction{PyMem_Malloc()} or
- \cfunction{PyMem_Realloc()}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyMem_Free}{void *p}
- Frees the memory block pointed to by \var{p}, which must have been
- returned by a previous call to \cfunction{PyMem_Malloc()} or
- \cfunction{PyMem_Realloc()}. Otherwise, or if
- \cfunction{PyMem_Free(p)} has been called before, undefined
- behavior occurs. If \var{p} is \NULL, no operation is performed.
-\end{cfuncdesc}
-
-The following type-oriented macros are provided for convenience. Note
-that \var{TYPE} refers to any C type.
-
-\begin{cfuncdesc}{\var{TYPE}*}{PyMem_New}{TYPE, size_t n}
- Same as \cfunction{PyMem_Malloc()}, but allocates \code{(\var{n} *
- sizeof(\var{TYPE}))} bytes of memory. Returns a pointer cast to
- \ctype{\var{TYPE}*}. The memory will not have been initialized in
- any way.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{\var{TYPE}*}{PyMem_Resize}{void *p, TYPE, size_t n}
- Same as \cfunction{PyMem_Realloc()}, but the memory block is resized
- to \code{(\var{n} * sizeof(\var{TYPE}))} bytes. Returns a pointer
- cast to \ctype{\var{TYPE}*}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyMem_Del}{void *p}
- Same as \cfunction{PyMem_Free()}.
-\end{cfuncdesc}
-
-In addition, the following macro sets are provided for calling the
-Python memory allocator directly, without involving the C API functions
-listed above. However, note that their use does not preserve binary
-compatibility accross Python versions and is therefore deprecated in
-extension modules.
-
-\cfunction{PyMem_MALLOC()}, \cfunction{PyMem_REALLOC()}, \cfunction{PyMem_FREE()}.
-
-\cfunction{PyMem_NEW()}, \cfunction{PyMem_RESIZE()}, \cfunction{PyMem_DEL()}.
-
-
-\section{Examples \label{memoryExamples}}
-
-Here is the example from section \ref{memoryOverview}, rewritten so
-that the I/O buffer is allocated from the Python heap by using the
-first function set:
-
-\begin{verbatim}
- PyObject *res;
- char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */
-
- if (buf == NULL)
- return PyErr_NoMemory();
- /* ...Do some I/O operation involving buf... */
- res = PyString_FromString(buf);
- PyMem_Free(buf); /* allocated with PyMem_Malloc */
- return res;
-\end{verbatim}
-
-The same code using the type-oriented function set:
-
-\begin{verbatim}
- PyObject *res;
- char *buf = PyMem_New(char, BUFSIZ); /* for I/O */
-
- if (buf == NULL)
- return PyErr_NoMemory();
- /* ...Do some I/O operation involving buf... */
- res = PyString_FromString(buf);
- PyMem_Del(buf); /* allocated with PyMem_New */
- return res;
-\end{verbatim}
-
-Note that in the two examples above, the buffer is always
-manipulated via functions belonging to the same set. Indeed, it
-is required to use the same memory API family for a given
-memory block, so that the risk of mixing different allocators is
-reduced to a minimum. The following code sequence contains two errors,
-one of which is labeled as \emph{fatal} because it mixes two different
-allocators operating on different heaps.
-
-\begin{verbatim}
-char *buf1 = PyMem_New(char, BUFSIZ);
-char *buf2 = (char *) malloc(BUFSIZ);
-char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
-...
-PyMem_Del(buf3); /* Wrong -- should be PyMem_Free() */
-free(buf2); /* Right -- allocated via malloc() */
-free(buf1); /* Fatal -- should be PyMem_Del() */
-\end{verbatim}
-
-In addition to the functions aimed at handling raw memory blocks from
-the Python heap, objects in Python are allocated and released with
-\cfunction{PyObject_New()}, \cfunction{PyObject_NewVar()} and
-\cfunction{PyObject_Del()}, or with their corresponding macros
-\cfunction{PyObject_NEW()}, \cfunction{PyObject_NEW_VAR()} and
-\cfunction{PyObject_DEL()}.
-
-These will be explained in the next chapter on defining and
-implementing new object types in C.
diff --git a/Doc/api/newtypes.tex b/Doc/api/newtypes.tex
deleted file mode 100644
index b7014c4070..0000000000
--- a/Doc/api/newtypes.tex
+++ /dev/null
@@ -1,1649 +0,0 @@
-\chapter{Object Implementation Support \label{newTypes}}
-
-
-This chapter describes the functions, types, and macros used when
-defining new object types.
-
-
-\section{Allocating Objects on the Heap
- \label{allocating-objects}}
-
-\begin{cfuncdesc}{PyObject*}{_PyObject_New}{PyTypeObject *type}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyVarObject*}{_PyObject_NewVar}{PyTypeObject *type, int size}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{_PyObject_Del}{PyObject *op}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyObject_Init}{PyObject *op,
- PyTypeObject *type}
- Initialize a newly-allocated object \var{op} with its type and
- initial reference. Returns the initialized object. If \var{type}
- indicates that the object participates in the cyclic garbage
- detector, it it added to the detector's set of observed objects.
- Other fields of the object are not affected.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyVarObject*}{PyObject_InitVar}{PyVarObject *op,
- PyTypeObject *type, int size}
- This does everything \cfunction{PyObject_Init()} does, and also
- initializes the length information for a variable-size object.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{\var{TYPE}*}{PyObject_New}{TYPE, PyTypeObject *type}
- Allocate a new Python object using the C structure type \var{TYPE}
- and the Python type object \var{type}. Fields not defined by the
- Python object header are not initialized; the object's reference
- count will be one. The size of the memory
- allocation is determined from the \member{tp_basicsize} field of the
- type object.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NewVar}{TYPE, PyTypeObject *type,
- int size}
- Allocate a new Python object using the C structure type \var{TYPE}
- and the Python type object \var{type}. Fields not defined by the
- Python object header are not initialized. The allocated memory
- allows for the \var{TYPE} structure plus \var{size} fields of the
- size given by the \member{tp_itemsize} field of \var{type}. This is
- useful for implementing objects like tuples, which are able to
- determine their size at construction time. Embedding the array of
- fields into the same allocation decreases the number of allocations,
- improving the memory management efficiency.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyObject_Del}{PyObject *op}
- Releases memory allocated to an object using
- \cfunction{PyObject_New()} or \cfunction{PyObject_NewVar()}. This
- is normally called from the \member{tp_dealloc} handler specified in
- the object's type. The fields of the object should not be accessed
- after this call as the memory is no longer a valid Python object.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW}{TYPE, PyTypeObject *type}
- Macro version of \cfunction{PyObject_New()}, to gain performance at
- the expense of safety. This does not check \var{type} for a \NULL{}
- value.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW_VAR}{TYPE, PyTypeObject *type,
- int size}
- Macro version of \cfunction{PyObject_NewVar()}, to gain performance
- at the expense of safety. This does not check \var{type} for a
- \NULL{} value.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyObject_DEL}{PyObject *op}
- Macro version of \cfunction{PyObject_Del()}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{Py_InitModule}{char *name,
- PyMethodDef *methods}
- Create a new module object based on a name and table of functions,
- returning the new module object.
-
- \versionchanged[Older versions of Python did not support \NULL{} as
- the value for the \var{methods} argument]{2.3}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{Py_InitModule3}{char *name,
- PyMethodDef *methods,
- char *doc}
- Create a new module object based on a name and table of functions,
- returning the new module object. If \var{doc} is non-\NULL, it will
- be used to define the docstring for the module.
-
- \versionchanged[Older versions of Python did not support \NULL{} as
- the value for the \var{methods} argument]{2.3}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{Py_InitModule4}{char *name,
- PyMethodDef *methods,
- char *doc, PyObject *self,
- int apiver}
- Create a new module object based on a name and table of functions,
- returning the new module object. If \var{doc} is non-\NULL, it will
- be used to define the docstring for the module. If \var{self} is
- non-\NULL, it will passed to the functions of the module as their
- (otherwise \NULL) first parameter. (This was added as an
- experimental feature, and there are no known uses in the current
- version of Python.) For \var{apiver}, the only value which should
- be passed is defined by the constant \constant{PYTHON_API_VERSION}.
-
- \note{Most uses of this function should probably be using
- the \cfunction{Py_InitModule3()} instead; only use this if you are
- sure you need it.}
-
- \versionchanged[Older versions of Python did not support \NULL{} as
- the value for the \var{methods} argument]{2.3}
-\end{cfuncdesc}
-
-DL_IMPORT
-
-\begin{cvardesc}{PyObject}{_Py_NoneStruct}
- Object which is visible in Python as \code{None}. This should only
- be accessed using the \code{Py_None} macro, which evaluates to a
- pointer to this object.
-\end{cvardesc}
-
-
-\section{Common Object Structures \label{common-structs}}
-
-There are a large number of structures which are used in the
-definition of object types for Python. This section describes these
-structures and how they are used.
-
-All Python objects ultimately share a small number of fields at the
-beginning of the object's representation in memory. These are
-represented by the \ctype{PyObject} and \ctype{PyVarObject} types,
-which are defined, in turn, by the expansions of some macros also
-used, whether directly or indirectly, in the definition of all other
-Python objects.
-
-\begin{ctypedesc}{PyObject}
- All object types are extensions of this type. This is a type which
- contains the information Python needs to treat a pointer to an
- object as an object. In a normal ``release'' build, it contains
- only the objects reference count and a pointer to the corresponding
- type object. It corresponds to the fields defined by the
- expansion of the \code{PyObject_VAR_HEAD} macro.
-\end{ctypedesc}
-
-\begin{ctypedesc}{PyVarObject}
- This is an extension of \ctype{PyObject} that adds the
- \member{ob_size} field. This is only used for objects that have
- some notion of \emph{length}. This type does not often appear in
- the Python/C API. It corresponds to the fields defined by the
- expansion of the \code{PyObject_VAR_HEAD} macro.
-\end{ctypedesc}
-
-These macros are used in the definition of \ctype{PyObject} and
-\ctype{PyVarObject}:
-
-\begin{csimplemacrodesc}{PyObject_HEAD}
- This is a macro which expands to the declarations of the fields of
- the \ctype{PyObject} type; it is used when declaring new types which
- represent objects without a varying length. The specific fields it
- expands to depends on the definition of
- \csimplemacro{Py_TRACE_REFS}. By default, that macro is not
- defined, and \csimplemacro{PyObject_HEAD} expands to:
- \begin{verbatim}
- int ob_refcnt;
- PyTypeObject *ob_type;
- \end{verbatim}
- When \csimplemacro{Py_TRACE_REFS} is defined, it expands to:
- \begin{verbatim}
- PyObject *_ob_next, *_ob_prev;
- int ob_refcnt;
- PyTypeObject *ob_type;
- \end{verbatim}
-\end{csimplemacrodesc}
-
-\begin{csimplemacrodesc}{PyObject_VAR_HEAD}
- This is a macro which expands to the declarations of the fields of
- the \ctype{PyVarObject} type; it is used when declaring new types which
- represent objects with a length that varies from instance to
- instance. This macro always expands to:
- \begin{verbatim}
- PyObject_HEAD
- int ob_size;
- \end{verbatim}
- Note that \csimplemacro{PyObject_HEAD} is part of the expansion, and
- that it's own expansion varies depending on the definition of
- \csimplemacro{Py_TRACE_REFS}.
-\end{csimplemacrodesc}
-
-PyObject_HEAD_INIT
-
-\begin{ctypedesc}{PyCFunction}
- Type of the functions used to implement most Python callables in C.
- Functions of this type take two \ctype{PyObject*} parameters and
- return one such value. If the return value is \NULL, an exception
- shall have been set. If not \NULL, the return value is interpreted
- as the return value of the function as exposed in Python. The
- function must return a new reference.
-\end{ctypedesc}
-
-\begin{ctypedesc}{PyMethodDef}
- Structure used to describe a method of an extension type. This
- structure has four fields:
-
- \begin{tableiii}{l|l|l}{member}{Field}{C Type}{Meaning}
- \lineiii{ml_name}{char *}{name of the method}
- \lineiii{ml_meth}{PyCFunction}{pointer to the C implementation}
- \lineiii{ml_flags}{int}{flag bits indicating how the call should be
- constructed}
- \lineiii{ml_doc}{char *}{points to the contents of the docstring}
- \end{tableiii}
-\end{ctypedesc}
-
-The \member{ml_meth} is a C function pointer. The functions may be of
-different types, but they always return \ctype{PyObject*}. If the
-function is not of the \ctype{PyCFunction}, the compiler will require
-a cast in the method table. Even though \ctype{PyCFunction} defines
-the first parameter as \ctype{PyObject*}, it is common that the method
-implementation uses a the specific C type of the \var{self} object.
-
-The \member{ml_flags} field is a bitfield which can include the
-following flags. The individual flags indicate either a calling
-convention or a binding convention. Of the calling convention flags,
-only \constant{METH_VARARGS} and \constant{METH_KEYWORDS} can be
-combined (but note that \constant{METH_KEYWORDS} alone is equivalent
-to \code{\constant{METH_VARARGS} | \constant{METH_KEYWORDS}}).
-Any of the calling convention flags can be combined with a
-binding flag.
-
-\begin{datadesc}{METH_VARARGS}
- This is the typical calling convention, where the methods have the
- type \ctype{PyCFunction}. The function expects two
- \ctype{PyObject*} values. The first one is the \var{self} object for
- methods; for module functions, it has the value given to
- \cfunction{Py_InitModule4()} (or \NULL{} if
- \cfunction{Py_InitModule()} was used). The second parameter
- (often called \var{args}) is a tuple object representing all
- arguments. This parameter is typically processed using
- \cfunction{PyArg_ParseTuple()} or \cfunction{PyArg_UnpackTuple}.
-\end{datadesc}
-
-\begin{datadesc}{METH_KEYWORDS}
- Methods with these flags must be of type
- \ctype{PyCFunctionWithKeywords}. The function expects three
- parameters: \var{self}, \var{args}, and a dictionary of all the
- keyword arguments. The flag is typically combined with
- \constant{METH_VARARGS}, and the parameters are typically processed
- using \cfunction{PyArg_ParseTupleAndKeywords()}.
-\end{datadesc}
-
-\begin{datadesc}{METH_NOARGS}
- Methods without parameters don't need to check whether arguments are
- given if they are listed with the \constant{METH_NOARGS} flag. They
- need to be of type \ctype{PyCFunction}. When used with object
- methods, the first parameter is typically named \code{self} and will
- hold a reference to the object instance. In all cases the second
- parameter will be \NULL.
-\end{datadesc}
-
-\begin{datadesc}{METH_O}
- Methods with a single object argument can be listed with the
- \constant{METH_O} flag, instead of invoking
- \cfunction{PyArg_ParseTuple()} with a \code{"O"} argument. They have
- the type \ctype{PyCFunction}, with the \var{self} parameter, and a
- \ctype{PyObject*} parameter representing the single argument.
-\end{datadesc}
-
-\begin{datadesc}{METH_OLDARGS}
- This calling convention is deprecated. The method must be of type
- \ctype{PyCFunction}. The second argument is \NULL{} if no arguments
- are given, a single object if exactly one argument is given, and a
- tuple of objects if more than one argument is given. There is no
- way for a function using this convention to distinguish between a
- call with multiple arguments and a call with a tuple as the only
- argument.
-\end{datadesc}
-
-These two constants are not used to indicate the calling convention
-but the binding when use with methods of classes. These may not be
-used for functions defined for modules. At most one of these flags
-may be set for any given method.
-
-\begin{datadesc}{METH_CLASS}
- The method will be passed the type object as the first parameter
- rather than an instance of the type. This is used to create
- \emph{class methods}, similar to what is created when using the
- \function{classmethod()}\bifuncindex{classmethod} built-in
- function.
- \versionadded{2.3}
-\end{datadesc}
-
-\begin{datadesc}{METH_STATIC}
- The method will be passed \NULL{} as the first parameter rather than
- an instance of the type. This is used to create \emph{static
- methods}, similar to what is created when using the
- \function{staticmethod()}\bifuncindex{staticmethod} built-in
- function.
- \versionadded{2.3}
-\end{datadesc}
-
-
-\begin{cfuncdesc}{PyObject*}{Py_FindMethod}{PyMethodDef table[],
- PyObject *ob, char *name}
- Return a bound method object for an extension type implemented in
- C. This can be useful in the implementation of a
- \member{tp_getattro} or \member{tp_getattr} handler that does not
- use the \cfunction{PyObject_GenericGetAttr()} function.
-\end{cfuncdesc}
-
-
-\section{Type Objects \label{type-structs}}
-
-Perhaps one of the most important structures of the Python object
-system is the structure that defines a new type: the
-\ctype{PyTypeObject} structure. Type objects can be handled using any
-of the \cfunction{PyObject_*()} or \cfunction{PyType_*()} functions,
-but do not offer much that's interesting to most Python applications.
-These objects are fundamental to how objects behave, so they are very
-important to the interpreter itself and to any extension module that
-implements new types.
-
-Type objects are fairly large compared to most of the standard types.
-The reason for the size is that each type object stores a large number
-of values, mostly C function pointers, each of which implements a
-small part of the type's functionality. The fields of the type object
-are examined in detail in this section. The fields will be described
-in the order in which they occur in the structure.
-
-Typedefs:
-unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
-intintargfunc, intobjargproc, intintobjargproc, objobjargproc,
-destructor, freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc,
-setattrofunc, cmpfunc, reprfunc, hashfunc
-
-The structure definition for \ctype{PyTypeObject} can be found in
-\file{Include/object.h}. For convenience of reference, this repeats
-the definition found there:
-
-\verbatiminput{typestruct.h}
-
-The type object structure extends the \ctype{PyVarObject} structure.
-The \member{ob_size} field is used for dynamic types (created
-by \function{type_new()}, usually called from a class statement).
-Note that \cdata{PyType_Type} (the metatype) initializes
-\member{tp_itemsize}, which means that its instances (i.e. type
-objects) \emph{must} have the \member{ob_size} field.
-
-\begin{cmemberdesc}{PyObject}{PyObject*}{_ob_next}
-\cmemberline{PyObject}{PyObject*}{_ob_prev}
- These fields are only present when the macro \code{Py_TRACE_REFS} is
- defined. Their initialization to \NULL{} is taken care of by the
- \code{PyObject_HEAD_INIT} macro. For statically allocated objects,
- these fields always remain \NULL. For dynamically allocated
- objects, these two fields are used to link the object into a
- doubly-linked list of \emph{all} live objects on the heap. This
- could be used for various debugging purposes; currently the only use
- is to print the objects that are still alive at the end of a run
- when the environment variable \envvar{PYTHONDUMPREFS} is set.
-
- These fields are not inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyObject}{int}{ob_refcnt}
- This is the type object's reference count, initialized to \code{1}
- by the \code{PyObject_HEAD_INIT} macro. Note that for statically
- allocated type objects, the type's instances (objects whose
- \member{ob_type} points back to the type) do \emph{not} count as
- references. But for dynamically allocated type objects, the
- instances \emph{do} count as references.
-
- This field is not inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyObject}{PyTypeObject*}{ob_type}
- This is the type's type, in other words its metatype. It is
- initialized by the argument to the \code{PyObject_HEAD_INIT} macro,
- and its value should normally be \code{\&PyType_Type}. However, for
- dynamically loadable extension modules that must be usable on
- Windows (at least), the compiler complains that this is not a valid
- initializer. Therefore, the convention is to pass \NULL{} to the
- \code{PyObject_HEAD_INIT} macro and to initialize this field
- explicitly at the start of the module's initialization function,
- before doing anything else. This is typically done like this:
-
-\begin{verbatim}
-Foo_Type.ob_type = &PyType_Type;
-\end{verbatim}
-
- This should be done before any instances of the type are created.
- \cfunction{PyType_Ready()} checks if \member{ob_type} is \NULL, and
- if so, initializes it: in Python 2.2, it is set to
- \code{\&PyType_Type}; in Python 2.2.1 and later it will be
- initialized to the \member{ob_type} field of the base class.
- \cfunction{PyType_Ready()} will not change this field if it is
- non-zero.
-
- In Python 2.2, this field is not inherited by subtypes. In 2.2.1,
- and in 2.3 and beyond, it is inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyVarObject}{int}{ob_size}
- For statically allocated type objects, this should be initialized
- to zero. For dynamically allocated type objects, this field has a
- special internal meaning.
-
- This field is not inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{char*}{tp_name}
- Pointer to a NUL-terminated string containing the name of the type.
- For types that are accessible as module globals, the string should
- be the full module name, followed by a dot, followed by the type
- name; for built-in types, it should be just the type name. If the
- module is a submodule of a package, the full package name is part of
- the full module name. For example, a type named \class{T} defined
- in module \module{M} in subpackage \module{Q} in package \module{P}
- should have the \member{tp_name} initializer \code{"P.Q.M.T"}.
-
- For dynamically allocated type objects, this should just be the type
- name, and the module name explicitly stored in the type dict as the
- value for key \code{'__module__'}.
-
- For statically allocated type objects, the tp_name field should
- contain a dot. Everything before the last dot is made accessible as
- the \member{__module__} attribute, and everything after the last dot
- is made accessible as the \member{__name__} attribute.
-
- If no dot is present, the entire \member{tp_name} field is made
- accessible as the \member{__name__} attribute, and the
- \member{__module__} attribute is undefined (unless explicitly set in
- the dictionary, as explained above). This means your type will be
- impossible to pickle.
-
- This field is not inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{int}{tp_basicsize}
-\cmemberline{PyTypeObject}{int}{tp_itemsize}
- These fields allow calculating the size in bytes of instances of
- the type.
-
- There are two kinds of types: types with fixed-length instances have
- a zero \member{tp_itemsize} field, types with variable-length
- instances have a non-zero \member{tp_itemsize} field. For a type
- with fixed-length instances, all instances have the same size,
- given in \member{tp_basicsize}.
-
- For a type with variable-length instances, the instances must have
- an \member{ob_size} field, and the instance size is
- \member{tp_basicsize} plus N times \member{tp_itemsize}, where N is
- the ``length'' of the object. The value of N is typically stored in
- the instance's \member{ob_size} field. There are exceptions: for
- example, long ints use a negative \member{ob_size} to indicate a
- negative number, and N is \code{abs(\member{ob_size})} there. Also,
- the presence of an \member{ob_size} field in the instance layout
- doesn't mean that the instance structure is variable-length (for
- example, the structure for the list type has fixed-length instances,
- yet those instances have a meaningful \member{ob_size} field).
-
- The basic size includes the fields in the instance declared by the
- macro \csimplemacro{PyObject_HEAD} or
- \csimplemacro{PyObject_VAR_HEAD} (whichever is used to declare the
- instance struct) and this in turn includes the \member{_ob_prev} and
- \member{_ob_next} fields if they are present. This means that the
- only correct way to get an initializer for the \member{tp_basicsize}
- is to use the \keyword{sizeof} operator on the struct used to
- declare the instance layout. The basic size does not include the GC
- header size (this is new in Python 2.2; in 2.1 and 2.0, the GC
- header size was included in \member{tp_basicsize}).
-
- These fields are inherited separately by subtypes. If the base type
- has a non-zero \member{tp_itemsize}, it is generally not safe to set
- \member{tp_itemsize} to a different non-zero value in a subtype
- (though this depends on the implementation of the base type).
-
- A note about alignment: if the variable items require a particular
- alignment, this should be taken care of by the value of
- \member{tp_basicsize}. Example: suppose a type implements an array
- of \code{double}. \member{tp_itemsize} is \code{sizeof(double)}.
- It is the programmer's responsibility that \member{tp_basicsize} is
- a multiple of \code{sizeof(double)} (assuming this is the alignment
- requirement for \code{double}).
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{destructor}{tp_dealloc}
- A pointer to the instance destructor function. This function must
- be defined unless the type guarantees that its instances will never
- be deallocated (as is the case for the singletons \code{None} and
- \code{Ellipsis}).
-
- The destructor function is called by the \cfunction{Py_DECREF()} and
- \cfunction{Py_XDECREF()} macros when the new reference count is
- zero. At this point, the instance is still in existance, but there
- are no references to it. The destructor function should free all
- references which the instance owns, free all memory buffers owned by
- the instance (using the freeing function corresponding to the
- allocation function used to allocate the buffer), and finally (as
- its last action) call the type's \member{tp_free} function. If the
- type is not subtypable (doesn't have the
- \constant{Py_TPFLAGS_BASETYPE} flag bit set), it is permissible to
- call the object deallocator directly instead of via
- \member{tp_free}. The object deallocator should be the one used to
- allocate the instance; this is normally \cfunction{PyObject_Del()}
- if the instance was allocated using \cfunction{PyObject_New()} or
- \cfunction{PyOject_VarNew()}, or \cfunction{PyObject_GC_Del()} if
- the instance was allocated using \cfunction{PyObject_GC_New()} or
- \cfunction{PyObject_GC_VarNew()}.
-
- This field is inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{printfunc}{tp_print}
- An optional pointer to the instance print function.
-
- The print function is only called when the instance is printed to a
- \emph{real} file; when it is printed to a pseudo-file (like a
- \class{StringIO} instance), the instance's \member{tp_repr} or
- \member{tp_str} function is called to convert it to a string. These
- are also called when the type's \member{tp_print} field is \NULL. A
- type should never implement \member{tp_print} in a way that produces
- different output than \member{tp_repr} or \member{tp_str} would.
-
- The print function is called with the same signature as
- \cfunction{PyObject_Print()}: \code{int tp_print(PyObject *self, FILE
- *file, int flags)}. The \var{self} argument is the instance to be
- printed. The \var{file} argument is the stdio file to which it is
- to be printed. The \var{flags} argument is composed of flag bits.
- The only flag bit currently defined is \constant{Py_PRINT_RAW}.
- When the \constant{Py_PRINT_RAW} flag bit is set, the instance
- should be printed the same way as \member{tp_str} would format it;
- when the \constant{Py_PRINT_RAW} flag bit is clear, the instance
- should be printed the same was as \member{tp_repr} would format it.
- It should return \code{-1} and set an exception condition when an
- error occurred during the comparison.
-
- It is possible that the \member{tp_print} field will be deprecated.
- In any case, it is recommended not to define \member{tp_print}, but
- instead to rely on \member{tp_repr} and \member{tp_str} for
- printing.
-
- This field is inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{getattrfunc}{tp_getattr}
- An optional pointer to the get-attribute-string function.
-
- This field is deprecated. When it is defined, it should point to a
- function that acts the same as the \member{tp_getattro} function,
- but taking a C string instead of a Python string object to give the
- attribute name. The signature is the same as for
- \cfunction{PyObject_GetAttrString()}.
-
- This field is inherited by subtypes together with
- \member{tp_getattro}: a subtype inherits both \member{tp_getattr}
- and \member{tp_getattro} from its base type when the subtype's
- \member{tp_getattr} and \member{tp_getattro} are both \NULL.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{setattrfunc}{tp_setattr}
- An optional pointer to the set-attribute-string function.
-
- This field is deprecated. When it is defined, it should point to a
- function that acts the same as the \member{tp_setattro} function,
- but taking a C string instead of a Python string object to give the
- attribute name. The signature is the same as for
- \cfunction{PyObject_SetAttrString()}.
-
- This field is inherited by subtypes together with
- \member{tp_setattro}: a subtype inherits both \member{tp_setattr}
- and \member{tp_setattro} from its base type when the subtype's
- \member{tp_setattr} and \member{tp_setattro} are both \NULL.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{cmpfunc}{tp_compare}
- An optional pointer to the three-way comparison function.
-
- The signature is the same as for \cfunction{PyObject_Compare()}.
- The function should return \code{1} if \var{self} greater than
- \var{other}, \code{0} if \var{self} is equal to \var{other}, and
- \code{-1} if \var{self} less than \var{other}. It should return
- \code{-1} and set an exception condition when an error occurred
- during the comparison.
-
- This field is inherited by subtypes together with
- \member{tp_richcompare} and \member{tp_hash}: a subtypes inherits
- all three of \member{tp_compare}, \member{tp_richcompare}, and
- \member{tp_hash} when the subtype's \member{tp_compare},
- \member{tp_richcompare}, and \member{tp_hash} are all \NULL.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{reprfunc}{tp_repr}
- An optional pointer to a function that implements the built-in
- function \function{repr()}.\bifuncindex{repr}
-
- The signature is the same as for \cfunction{PyObject_Repr()}; it
- must return a string or a Unicode object. Ideally, this function
- should return a string that, when passed to \function{eval()}, given
- a suitable environment, returns an object with the same value. If
- this is not feasible, it should return a string starting with
- \character{\textless} and ending with \character{\textgreater} from
- which both the type and the value of the object can be deduced.
-
- When this field is not set, a string of the form \samp{<\%s object
- at \%p>} is returned, where \code{\%s} is replaced by the type name,
- and \code{\%p} by the object's memory address.
-
- This field is inherited by subtypes.
-\end{cmemberdesc}
-
-PyNumberMethods *tp_as_number;
-
- XXX
-
-PySequenceMethods *tp_as_sequence;
-
- XXX
-
-PyMappingMethods *tp_as_mapping;
-
- XXX
-
-\begin{cmemberdesc}{PyTypeObject}{hashfunc}{tp_hash}
- An optional pointer to a function that implements the built-in
- function \function{hash()}.\bifuncindex{hash}
-
- The signature is the same as for \cfunction{PyObject_Hash()}; it
- must return a C long. The value \code{-1} should not be returned as
- a normal return value; when an error occurs during the computation
- of the hash value, the function should set an exception and return
- \code{-1}.
-
- When this field is not set, two possibilities exist: if the
- \member{tp_compare} and \member{tp_richcompare} fields are both
- \NULL, a default hash value based on the object's address is
- returned; otherwise, a \exception{TypeError} is raised.
-
- This field is inherited by subtypes together with
- \member{tp_richcompare} and \member{tp_compare}: a subtypes inherits
- all three of \member{tp_compare}, \member{tp_richcompare}, and
- \member{tp_hash}, when the subtype's \member{tp_compare},
- \member{tp_richcompare} and \member{tp_hash} are all \NULL.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{ternaryfunc}{tp_call}
- An optional pointer to a function that implements calling the
- object. This should be \NULL{} if the object is not callable. The
- signature is the same as for \cfunction{PyObject_Call()}.
-
- This field is inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{reprfunc}{tp_str}
- An optional pointer to a function that implements the built-in
- operation \function{str()}. (Note that \class{str} is a type now,
- and \function{str()} calls the constructor for that type. This
- constructor calls \cfunction{PyObject_Str()} to do the actual work,
- and \cfunction{PyObject_Str()} will call this handler.)
-
- The signature is the same as for \cfunction{PyObject_Str()}; it must
- return a string or a Unicode object. This function should return a
- ``friendly'' string representation of the object, as this is the
- representation that will be used by the print statement.
-
- When this field is not set, \cfunction{PyObject_Repr()} is called to
- return a string representation.
-
- This field is inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{getattrofunc}{tp_getattro}
- An optional pointer to the get-attribute function.
-
- The signature is the same as for \cfunction{PyObject_GetAttr()}. It
- is usually convenient to set this field to
- \cfunction{PyObject_GenericGetAttr()}, which implements the normal
- way of looking for object attributes.
-
- This field is inherited by subtypes together with
- \member{tp_getattr}: a subtype inherits both \member{tp_getattr} and
- \member{tp_getattro} from its base type when the subtype's
- \member{tp_getattr} and \member{tp_getattro} are both \NULL.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{setattrofunc}{tp_setattro}
- An optional pointer to the set-attribute function.
-
- The signature is the same as for \cfunction{PyObject_SetAttr()}. It
- is usually convenient to set this field to
- \cfunction{PyObject_GenericSetAttr()}, which implements the normal
- way of setting object attributes.
-
- This field is inherited by subtypes together with
- \member{tp_setattr}: a subtype inherits both \member{tp_setattr} and
- \member{tp_setattro} from its base type when the subtype's
- \member{tp_setattr} and \member{tp_setattro} are both \NULL.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{PyBufferProcs*}{tp_as_buffer}
- Pointer to an additional structure contains fields relevant only to
- objects which implement the buffer interface. These fields are
- documented in ``Buffer Object Structures'' (section
- \ref{buffer-structs}).
-
- The \member{tp_as_buffer} field is not inherited, but the contained
- fields are inherited individually.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{long}{tp_flags}
- This field is a bit mask of various flags. Some flags indicate
- variant semantics for certain situations; others are used to
- indicate that certain fields in the type object (or in the extension
- structures referenced via \member{tp_as_number},
- \member{tp_as_sequence}, \member{tp_as_mapping}, and
- \member{tp_as_buffer}) that were historically not always present are
- valid; if such a flag bit is clear, the type fields it guards must
- not be accessed and must be considered to have a zero or \NULL{}
- value instead.
-
- Inheritance of this field is complicated. Most flag bits are
- inherited individually, i.e. if the base type has a flag bit set,
- the subtype inherits this flag bit. The flag bits that pertain to
- extension structures are strictly inherited if the extension
- structure is inherited, i.e. the base type's value of the flag bit
- is copied into the subtype together with a pointer to the extension
- structure. The \constant{Py_TPFLAGS_HAVE_GC} flag bit is inherited
- together with the \member{tp_traverse} and \member{tp_clear} fields,
- i.e. if the \constant{Py_TPFLAGS_HAVE_GC} flag bit is clear in the
- subtype and the \member{tp_traverse} and \member{tp_clear} fields in
- the subtype exist (as indicated by the
- \constant{Py_TPFLAGS_HAVE_RICHCOMPARE} flag bit) and have \NULL{}
- values.
-
- The following bit masks are currently defined; these can be or-ed
- together using the \code{|} operator to form the value of the
- \member{tp_flags} field. The macro \cfunction{PyType_HasFeature()}
- takes a type and a flags value, \var{tp} and \var{f}, and checks
- whether \code{\var{tp}->tp_flags \& \var{f}} is non-zero.
-
- \begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
- If this bit is set, the \ctype{PyBufferProcs} struct referenced by
- \member{tp_as_buffer} has the \member{bf_getcharbuffer} field.
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_HAVE_SEQUENCE_IN}
- If this bit is set, the \ctype{PySequenceMethods} struct
- referenced by \member{tp_as_sequence} has the \member{sq_contains}
- field.
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_GC}
- This bit is obsolete. The bit it used to name is no longer in
- use. The symbol is now defined as zero.
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_HAVE_INPLACEOPS}
- If this bit is set, the \ctype{PySequenceMethods} struct
- referenced by \member{tp_as_sequence} and the
- \ctype{PyNumberMethods} structure referenced by
- \member{tp_as_number} contain the fields for in-place operators.
- In particular, this means that the \ctype{PyNumberMethods}
- structure has the fields \member{nb_inplace_add},
- \member{nb_inplace_subtract}, \member{nb_inplace_multiply},
- \member{nb_inplace_divide}, \member{nb_inplace_remainder},
- \member{nb_inplace_power}, \member{nb_inplace_lshift},
- \member{nb_inplace_rshift}, \member{nb_inplace_and},
- \member{nb_inplace_xor}, and \member{nb_inplace_or}; and the
- \ctype{PySequenceMethods} struct has the fields
- \member{sq_inplace_concat} and \member{sq_inplace_repeat}.
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_CHECKTYPES}
- If this bit is set, the binary and ternary operations in the
- \ctype{PyNumberMethods} structure referenced by
- \member{tp_as_number} accept arguments of arbitrary object types,
- and do their own type conversions if needed. If this bit is
- clear, those operations require that all arguments have the
- current type as their type, and the caller is supposed to perform
- a coercion operation first. This applies to \member{nb_add},
- \member{nb_subtract}, \member{nb_multiply}, \member{nb_divide},
- \member{nb_remainder}, \member{nb_divmod}, \member{nb_power},
- \member{nb_lshift}, \member{nb_rshift}, \member{nb_and},
- \member{nb_xor}, and \member{nb_or}.
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_HAVE_RICHCOMPARE}
- If this bit is set, the type object has the
- \member{tp_richcompare} field, as well as the \member{tp_traverse}
- and the \member{tp_clear} fields.
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_HAVE_WEAKREFS}
- If this bit is set, the \member{tp_weaklistoffset} field is
- defined. Instances of a type are weakly referenceable if the
- type's \member{tp_weaklistoffset} field has a value greater than
- zero.
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_HAVE_ITER}
- If this bit is set, the type object has the \member{tp_iter} and
- \member{tp_iternext} fields.
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_HAVE_CLASS}
- If this bit is set, the type object has several new fields defined
- starting in Python 2.2: \member{tp_methods}, \member{tp_members},
- \member{tp_getset}, \member{tp_base}, \member{tp_dict},
- \member{tp_descr_get}, \member{tp_descr_set},
- \member{tp_dictoffset}, \member{tp_init}, \member{tp_alloc},
- \member{tp_new}, \member{tp_free}, \member{tp_is_gc},
- \member{tp_bases}, \member{tp_mro}, \member{tp_cache},
- \member{tp_subclasses}, and \member{tp_weaklist}.
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_HEAPTYPE}
- This bit is set when the type object itself is allocated on the
- heap. In this case, the \member{ob_type} field of its instances
- is considered a reference to the type, and the type object is
- INCREF'ed when a new instance is created, and DECREF'ed when an
- instance is destroyed (this does not apply to instances of
- subtypes; only the type referenced by the instance's ob_type gets
- INCREF'ed or DECREF'ed).
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_BASETYPE}
- This bit is set when the type can be used as the base type of
- another type. If this bit is clear, the type cannot be subtyped
- (similar to a "final" class in Java).
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_READY}
- This bit is set when the type object has been fully initialized by
- \cfunction{PyType_Ready()}.
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_READYING}
- This bit is set while \cfunction{PyType_Ready()} is in the process
- of initializing the type object.
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_HAVE_GC}
- This bit is set when the object supports garbage collection. If
- this bit is set, instances must be created using
- \cfunction{PyObject_GC_New()} and destroyed using
- \cfunction{PyObject_GC_Del()}. More information in section XXX
- about garbage collection. This bit also implies that the
- GC-related fields \member{tp_traverse} and \member{tp_clear} are
- present in the type object; but those fields also exist when
- \constant{Py_TPFLAGS_HAVE_GC} is clear but
- \constant{Py_TPFLAGS_HAVE_RICHCOMPARE} is set).
- \end{datadesc}
-
- \begin{datadesc}{Py_TPFLAGS_DEFAULT}
- This is a bitmask of all the bits that pertain to the existence of
- certain fields in the type object and its extension structures.
- Currently, it includes the following bits:
- \constant{Py_TPFLAGS_HAVE_GETCHARBUFFER},
- \constant{Py_TPFLAGS_HAVE_SEQUENCE_IN},
- \constant{Py_TPFLAGS_HAVE_INPLACEOPS},
- \constant{Py_TPFLAGS_HAVE_RICHCOMPARE},
- \constant{Py_TPFLAGS_HAVE_WEAKREFS},
- \constant{Py_TPFLAGS_HAVE_ITER}, and
- \constant{Py_TPFLAGS_HAVE_CLASS}.
- \end{datadesc}
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{char*}{tp_doc}
- An optional pointer to a NUL-terminated C string giving the
- docstring for this type object. This is exposed as the
- \member{__doc__} attribute on the type and instances of the type.
-
- This field is \emph{not} inherited by subtypes.
-\end{cmemberdesc}
-
-The following three fields only exist if the
-\constant{Py_TPFLAGS_HAVE_RICHCOMPARE} flag bit is set.
-
-\begin{cmemberdesc}{PyTypeObject}{traverseproc}{tp_traverse}
- An optional pointer to a traversal function for the garbage
- collector. This is only used if the \constant{Py_TPFLAGS_HAVE_GC}
- flag bit is set. More information in section
- \ref{supporting-cycle-detection} about garbage collection.
-
- This field is inherited by subtypes together with \member{tp_clear}
- and the \constant{Py_TPFLAGS_HAVE_GC} flag bit: the flag bit,
- \member{tp_traverse}, and \member{tp_clear} are all inherited from
- the base type if they are all zero in the subtype \emph{and} the
- subtype has the \constant{Py_TPFLAGS_HAVE_RICHCOMPARE} flag bit set.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{inquiry}{tp_clear}
- An optional pointer to a clear function for the garbage collector.
- This is only used if the \constant{Py_TPFLAGS_HAVE_GC} flag bit is
- set. More information in section
- \ref{supporting-cycle-detection} about garbage collection.
-
- This field is inherited by subtypes together with \member{tp_clear}
- and the \constant{Py_TPFLAGS_HAVE_GC} flag bit: the flag bit,
- \member{tp_traverse}, and \member{tp_clear} are all inherited from
- the base type if they are all zero in the subtype \emph{and} the
- subtype has the \constant{Py_TPFLAGS_HAVE_RICHCOMPARE} flag bit set.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{richcmpfunc}{tp_richcompare}
- An optional pointer to the rich comparison function.
-
- The signature is the same as for \cfunction{PyObject_RichCompare()}.
- The function should return \code{1} if the requested comparison
- returns true, \code{0} if it returns false. It should return
- \code{-1} and set an exception condition when an error occurred
- during the comparison.
-
- This field is inherited by subtypes together with
- \member{tp_compare} and \member{tp_hash}: a subtype inherits all
- three of \member{tp_compare}, \member{tp_richcompare}, and
- \member{tp_hash}, when the subtype's \member{tp_compare},
- \member{tp_richcompare}, and \member{tp_hash} are all \NULL.
-
- The following constants are defined to be used as the third argument
- for \member{tp_richcompare} and for \cfunction{PyObject_RichCompare()}:
-
- \begin{tableii}{l|c}{constant}{Constant}{Comparison}
- \lineii{Py_LT}{\code{<}}
- \lineii{Py_LE}{\code{<=}}
- \lineii{Py_EQ}{\code{==}}
- \lineii{Py_NE}{\code{!=}}
- \lineii{Py_GT}{\code{>}}
- \lineii{Py_GE}{\code{>=}}
- \end{tableii}
-\end{cmemberdesc}
-
-The next field only exists if the \constant{Py_TPFLAGS_HAVE_WEAKREFS}
-flag bit is set.
-
-\begin{cmemberdesc}{PyTypeObject}{long}{tp_weaklistoffset}
- If the instances of this type are weakly referenceable, this field
- is greater than zero and contains the offset in the instance
- structure of the weak reference list head (ignoring the GC header,
- if present); this offset is used by
- \cfunction{PyObject_ClearWeakRefs()} and the
- \cfunction{PyWeakref_*()} functions. The instance structure needs
- to include a field of type \ctype{PyObject*} which is initialized to
- \NULL.
-
- Do not confuse this field with \member{tp_weaklist}; that is the
- list head for weak references to the type object itself.
-
- This field is inherited by subtypes, but see the rules listed below.
- A subtype may override this offset; this means that the subtype uses
- a different weak reference list head than the base type. Since the
- list head is always found via \member{tp_weaklistoffset}, this
- should not be a problem.
-
- When a type defined by a class statement has no \member{__slots__}
- declaration, and none of its base types are weakly referenceable,
- the type is made weakly referenceable by adding a weak reference
- list head slot to the instance layout and setting the
- \member{tp_weaklistoffset} of that slot's offset.
-
- When a type's \member{__slots__} declaration contains a slot named
- \member{__weakref__}, that slot becomes the weak reference list head
- for instances of the type, and the slot's offset is stored in the
- type's \member{tp_weaklistoffset}.
-
- When a type's \member{__slots__} declaration does not contain a slot
- named \member{__weakref__}, the type inherits its
- \member{tp_weaklistoffset} from its base type.
-\end{cmemberdesc}
-
-The next two fields only exist if the
-\constant{Py_TPFLAGS_HAVE_CLASS} flag bit is set.
-
-\begin{cmemberdesc}{PyTypeObject}{getiterfunc}{tp_iter}
- An optional pointer to a function that returns an iterator for the
- object. Its presence normally signals that the instances of this
- type are iterable (although sequences may be iterable without this
- function, and classic instances always have this function, even if
- they don't define an \method{__iter__()} method).
-
- This function has the same signature as
- \cfunction{PyObject_GetIter()}.
-
- This field is inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{iternextfunc}{tp_iternext}
- An optional pointer to a function that returns the next item in an
- iterator, or raises \exception{StopIteration} when the iterator is
- exhausted. Its presence normally signals that the instances of this
- type are iterators (although classic instances always have this
- function, even if they don't define a \method{next()} method).
-
- Iterator types should also define the \member{tp_iter} function, and
- that function should return the iterator instance itself (not a new
- iterator instance).
-
- This function has the same signature as \cfunction{PyIter_Next()}.
-
- This field is inherited by subtypes.
-\end{cmemberdesc}
-
-The next fields, up to and including \member{tp_weaklist}, only exist
-if the \constant{Py_TPFLAGS_HAVE_CLASS} flag bit is set.
-
-\begin{cmemberdesc}{PyTypeObject}{struct PyMethodDef*}{tp_methods}
- An optional pointer to a static \NULL-terminated array of
- \ctype{PyMethodDef} structures, declaring regular methods of this
- type.
-
- For each entry in the array, an entry is added to the type's
- dictionary (see \member{tp_dict} below) containing a method
- descriptor.
-
- This field is not inherited by subtypes (methods are
- inherited through a different mechanism).
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{struct PyMemberDef*}{tp_members}
- An optional pointer to a static \NULL-terminated array of
- \ctype{PyMemberDef} structures, declaring regular data members
- (fields or slots) of instances of this type.
-
- For each entry in the array, an entry is added to the type's
- dictionary (see \member{tp_dict} below) containing a member
- descriptor.
-
- This field is not inherited by subtypes (members are inherited
- through a different mechanism).
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{struct PyGetSetDef*}{tp_getset}
- An optional pointer to a static \NULL-terminated array of
- \ctype{PyGetSetDef} structures, declaring computed attributes of
- instances of this type.
-
- For each entry in the array, an entry is added to the type's
- dictionary (see \member{tp_dict} below) containing a getset
- descriptor.
-
- This field is not inherited by subtypes (computed attributes are
- inherited through a different mechanism).
-
- Docs for PyGetSetDef (XXX belong elsewhere):
-
-\begin{verbatim}
-typedef PyObject *(*getter)(PyObject *, void *);
-typedef int (*setter)(PyObject *, PyObject *, void *);
-
-typedef struct PyGetSetDef {
- char *name; /* attribute name */
- getter get; /* C function to get the attribute */
- setter set; /* C function to set the attribute */
- char *doc; /* optional doc string */
- void *closure; /* optional additional data for getter and setter */
-} PyGetSetDef;
-\end{verbatim}
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{PyTypeObject*}{tp_base}
- An optional pointer to a base type from which type properties are
- inherited. At this level, only single inheritance is supported;
- multiple inheritance require dynamically creating a type object by
- calling the metatype.
-
- This field is not inherited by subtypes (obviously), but it defaults
- to \code{\&PyBaseObject_Type} (which to Python programmers is known
- as the type \class{object}).
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{PyObject*}{tp_dict}
- The type's dictionary is stored here by \cfunction{PyType_Ready()}.
-
- This field should normally be initialized to \NULL{} before
- PyType_Ready is called; it may also be initialized to a dictionary
- containing initial attributes for the type. Once
- \cfunction{PyType_Ready()} has initialized the type, extra
- attributes for the type may be added to this dictionary only if they
- don't correspond to overloaded operations (like \method{__add__()}).
-
- This field is not inherited by subtypes (though the attributes
- defined in here are inherited through a different mechanism).
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{descrgetfunc}{tp_descr_get}
- An optional pointer to a "descriptor get" function.
-
- XXX blah, blah.
-
- This field is inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{descrsetfunc}{tp_descr_set}
- An optional pointer to a "descriptor set" function.
-
- XXX blah, blah.
-
- This field is inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{long}{tp_dictoffset}
- If the instances of this type have a dictionary containing instance
- variables, this field is non-zero and contains the offset in the
- instances of the type of the instance variable dictionary; this
- offset is used by \cfunction{PyObject_GenericGetAttr()}.
-
- Do not confuse this field with \member{tp_dict}; that is the
- dictionary for attributes of the type object itself.
-
- If the value of this field is greater than zero, it specifies the
- offset from the start of the instance structure. If the value is
- less than zero, it specifies the offset from the *end* of the
- instance structure. A negative offset is more expensive to use, and
- should only be used when the instance structure contains a
- variable-length part. This is used for example to add an instance
- variable dictionary to subtypes of \class{str} or \class{tuple}.
- Note that the \member{tp_basicsize} field should account for the
- dictionary added to the end in that case, even though the dictionary
- is not included in the basic object layout. On a system with a
- pointer size of 4 bytes, \member{tp_dictoffset} should be set to
- \code{-4} to indicate that the dictionary is at the very end of the
- structure.
-
- The real dictionary offset in an instance can be computed from a
- negative \member{tp_dictoffset} as follows:
-
-\begin{verbatim}
-dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset
-if dictoffset is not aligned on sizeof(void*):
- round up to sizeof(void*)
-\end{verbatim}
-
- where \member{tp_basicsize}, \member{tp_itemsize} and
- \member{tp_dictoffset} are taken from the type object, and
- \member{ob_size} is taken from the instance. The absolute value is
- taken because long ints use the sign of \member{ob_size} to store
- the sign of the number. (There's never a need to do this
- calculation yourself; it is done for you by
- \cfunction{_PyObject_GetDictPtr()}.)
-
- This field is inherited by subtypes, but see the rules listed below.
- A subtype may override this offset; this means that the subtype
- instances store the dictionary at a difference offset than the base
- type. Since the dictionary is always found via
- \member{tp_dictoffset}, this should not be a problem.
-
- When a type defined by a class statement has no \member{__slots__}
- declaration, and none of its base types has an instance variable
- dictionary, a dictionary slot is added to the instance layout and
- the \member{tp_dictoffset} is set to that slot's offset.
-
- When a type defined by a class statement has a \member{__slots__}
- declaration, the type inherits its \member{tp_dictoffset} from its
- base type.
-
- (Adding a slot named \member{__dict__} to the \member{__slots__}
- declaration does not have the expected effect, it just causes
- confusion. Maybe this should be added as a feature just like
- \member{__weakref__} though.)
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{initproc}{tp_init}
- An optional pointer to an instance initialization function.
-
- This function corresponds to the \method{__init__()} method of
- classes. Like \method{__init__()}, it is possible to create an
- instance without calling \method{__init__()}, and it is possible to
- reinitialize an instance by calling its \method{__init__()} method
- again.
-
- The function signature is
-
-\begin{verbatim}
-int tp_init(PyObject *self, PyObject *args, PyObject *kwds)
-\end{verbatim}
-
- The self argument is the instance to be initialized; the \var{args}
- and \var{kwds} arguments represent positional and keyword arguments
- of the call to \method{__init__()}.
-
- The \member{tp_init} function, if not \NULL, is called when an
- instance is created normally by calling its type, after the type's
- \member{tp_new} function has returned an instance of the type. If
- the \member{tp_new} function returns an instance of some other type
- that is not a subtype of the original type, no \member{tp_init}
- function is called; if \member{tp_new} returns an instance of a
- subtype of the original type, the subtype's \member{tp_init} is
- called. (VERSION NOTE: described here is what is implemented in
- Python 2.2.1 and later. In Python 2.2, the \member{tp_init} of the
- type of the object returned by \member{tp_new} was always called, if
- not \NULL.)
-
- This field is inherited by subtypes.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{allocfunc}{tp_alloc}
- An optional pointer to an instance allocation function.
-
- The function signature is
-
-\begin{verbatim}
-PyObject *tp_alloc(PyTypeObject *self, int nitems)
-\end{verbatim}
-
- The purpose of this function is to separate memory allocation from
- memory initialization. It should return a pointer to a block of
- memory of adequate length for the instance, suitably aligned, and
- initialized to zeros, but with \member{ob_refcnt} set to \code{1}
- and \member{ob_type} set to the type argument. If the type's
- \member{tp_itemsize} is non-zero, the object's \member{ob_size} field
- should be initialized to \var{nitems} and the length of the
- allocated memory block should be \code{tp_basicsize +
- \var{nitems}*tp_itemsize}, rounded up to a multiple of
- \code{sizeof(void*)}; otherwise, \var{nitems} is not used and the
- length of the block should be \member{tp_basicsize}.
-
- Do not use this function to do any other instance initialization,
- not even to allocate additional memory; that should be done by
- \member{tp_new}.
-
- This field is inherited by static subtypes, but not by dynamic
- subtypes (subtypes created by a class statement); in the latter,
- this field is always set to \cfunction{PyType_GenericAlloc()}, to
- force a standard heap allocation strategy. That is also the
- recommended value for statically defined types.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{newfunc}{tp_new}
- An optional pointer to an instance creation function.
-
- If this function is \NULL{} for a particular type, that type cannot
- be called to create new instances; presumably there is some other
- way to create instances, like a factory function.
-
- The function signature is
-
-\begin{verbatim}
-PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
-\end{verbatim}
-
- The subtype argument is the type of the object being created; the
- \var{args} and \var{kwds} arguments represent positional and keyword
- arguments of the call to the type. Note that subtype doesn't have
- to equal the type whose \member{tp_new} function is called; it may
- be a subtype of that type (but not an unrelated type).
-
- The \member{tp_new} function should call
- \code{\var{subtype}->tp_alloc(\var{subtype}, \var{nitems})} to
- allocate space for the object, and then do only as much further
- initialization as is absolutely necessary. Initialization that can
- safely be ignored or repeated should be placed in the
- \member{tp_init} handler. A good rule of thumb is that for
- immutable types, all initialization should take place in
- \member{tp_new}, while for mutable types, most initialization should
- be deferred to \member{tp_init}.
-
- This field is inherited by subtypes, except it is not inherited by
- static types whose \member{tp_base} is \NULL{} or
- \code{\&PyBaseObject_Type}. The latter exception is a precaution so
- that old extension types don't become callable simply by being
- linked with Python 2.2.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{destructor}{tp_free}
- An optional pointer to an instance deallocation function.
-
- The signature of this function has changed slightly: in Python
- 2.2 and 2.2.1, its signature is \ctype{destructor}:
-
-\begin{verbatim}
-void tp_free(PyObject *)
-\end{verbatim}
-
- In Python 2.3 and beyond, its signature is \ctype{freefunc}:
-
-\begin{verbatim}
-void tp_free(void *)
-\end{verbatim}
-
- The only initializer that is compatible with both versions is
- \code{_PyObject_Del}, whose definition has suitably adapted in
- Python 2.3.
-
- This field is inherited by static subtypes, but not by dynamic
- subtypes (subtypes created by a class statement); in the latter,
- this field is set to a deallocator suitable to match
- \cfunction{PyType_GenericAlloc()} and the value of the
- \constant{Py_TPFLAGS_HAVE_GC} flag bit.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{inquiry}{tp_is_gc}
- An optional pointer to a function called by the garbage collector.
-
- The garbage collector needs to know whether a particular object is
- collectible or not. Normally, it is sufficient to look at the
- object's type's \member{tp_flags} field, and check the
- \constant{Py_TPFLAGS_HAVE_GC} flag bit. But some types have a
- mixture of statically and dynamically allocated instances, and the
- statically allocated instances are not collectible. Such types
- should define this function; it should return \code{1} for a
- collectible instance, and \code{0} for a non-collectible instance.
- The signature is
-
-\begin{verbatim}
-int tp_is_gc(PyObject *self)
-\end{verbatim}
-
- (The only example of this are types themselves. The metatype,
- \cdata{PyType_Type}, defines this function to distinguish between
- statically and dynamically allocated types.)
-
- This field is inherited by subtypes. (VERSION NOTE: in Python
- 2.2, it was not inherited. It is inherited in 2.2.1 and later
- versions.)
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{PyObject*}{tp_bases}
- Tuple of base types.
-
- This is set for types created by a class statement. It should be
- \NULL{} for statically defined types.
-
- This field is not inherited.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{PyObject*}{tp_mro}
- Tuple containing the expanded set of base types, starting with the
- type itself and ending with \class{object}, in Method Resolution
- Order.
-
- This field is not inherited; it is calculated fresh by
- \cfunction{PyType_Ready()}.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{PyObject*}{tp_cache}
- Unused. Not inherited. Internal use only.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{PyObject*}{tp_subclasses}
- List of weak references to subclasses. Not inherited. Internal
- use only.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{PyObject*}{tp_weaklist}
- Weak reference list head, for weak references to this type
- object. Not inherited. Internal use only.
-\end{cmemberdesc}
-
-The remaining fields are only defined if the feature test macro
-\constant{COUNT_ALLOCS} is defined, and are for internal use only.
-They are documented here for completeness. None of these fields are
-inherited by subtypes.
-
-\begin{cmemberdesc}{PyTypeObject}{int}{tp_allocs}
- Number of allocations.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{int}{tp_frees}
- Number of frees.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{int}{tp_maxalloc}
- Maximum simultaneously allocated objects.
-\end{cmemberdesc}
-
-\begin{cmemberdesc}{PyTypeObject}{PyTypeObject*}{tp_next}
- Pointer to the next type object with a non-zero \member{tp_allocs}
- field.
-\end{cmemberdesc}
-
-
-\section{Mapping Object Structures \label{mapping-structs}}
-
-\begin{ctypedesc}{PyMappingMethods}
- Structure used to hold pointers to the functions used to implement
- the mapping protocol for an extension type.
-\end{ctypedesc}
-
-
-\section{Number Object Structures \label{number-structs}}
-
-\begin{ctypedesc}{PyNumberMethods}
- Structure used to hold pointers to the functions an extension type
- uses to implement the number protocol.
-\end{ctypedesc}
-
-
-\section{Sequence Object Structures \label{sequence-structs}}
-
-\begin{ctypedesc}{PySequenceMethods}
- Structure used to hold pointers to the functions which an object
- uses to implement the sequence protocol.
-\end{ctypedesc}
-
-
-\section{Buffer Object Structures \label{buffer-structs}}
-\sectionauthor{Greg J. Stein}{greg@lyra.org}
-
-The buffer interface exports a model where an object can expose its
-internal data as a set of chunks of data, where each chunk is
-specified as a pointer/length pair. These chunks are called
-\dfn{segments} and are presumed to be non-contiguous in memory.
-
-If an object does not export the buffer interface, then its
-\member{tp_as_buffer} member in the \ctype{PyTypeObject} structure
-should be \NULL. Otherwise, the \member{tp_as_buffer} will point to
-a \ctype{PyBufferProcs} structure.
-
-\note{It is very important that your \ctype{PyTypeObject} structure
-uses \constant{Py_TPFLAGS_DEFAULT} for the value of the
-\member{tp_flags} member rather than \code{0}. This tells the Python
-runtime that your \ctype{PyBufferProcs} structure contains the
-\member{bf_getcharbuffer} slot. Older versions of Python did not have
-this member, so a new Python interpreter using an old extension needs
-to be able to test for its presence before using it.}
-
-\begin{ctypedesc}{PyBufferProcs}
- Structure used to hold the function pointers which define an
- implementation of the buffer protocol.
-
- The first slot is \member{bf_getreadbuffer}, of type
- \ctype{getreadbufferproc}. If this slot is \NULL, then the object
- does not support reading from the internal data. This is
- non-sensical, so implementors should fill this in, but callers
- should test that the slot contains a non-\NULL{} value.
-
- The next slot is \member{bf_getwritebuffer} having type
- \ctype{getwritebufferproc}. This slot may be \NULL{} if the object
- does not allow writing into its returned buffers.
-
- The third slot is \member{bf_getsegcount}, with type
- \ctype{getsegcountproc}. This slot must not be \NULL{} and is used
- to inform the caller how many segments the object contains. Simple
- objects such as \ctype{PyString_Type} and \ctype{PyBuffer_Type}
- objects contain a single segment.
-
- The last slot is \member{bf_getcharbuffer}, of type
- \ctype{getcharbufferproc}. This slot will only be present if the
- \constant{Py_TPFLAGS_HAVE_GETCHARBUFFER} flag is present in the
- \member{tp_flags} field of the object's \ctype{PyTypeObject}.
- Before using this slot, the caller should test whether it is present
- by using the
- \cfunction{PyType_HasFeature()}\ttindex{PyType_HasFeature()}
- function. If present, it may be \NULL, indicating that the object's
- contents cannot be used as \emph{8-bit characters}.
- The slot function may also raise an error if the object's contents
- cannot be interpreted as 8-bit characters. For example, if the
- object is an array which is configured to hold floating point
- values, an exception may be raised if a caller attempts to use
- \member{bf_getcharbuffer} to fetch a sequence of 8-bit characters.
- This notion of exporting the internal buffers as ``text'' is used to
- distinguish between objects that are binary in nature, and those
- which have character-based content.
-
- \note{The current policy seems to state that these characters
- may be multi-byte characters. This implies that a buffer size of
- \var{N} does not mean there are \var{N} characters present.}
-\end{ctypedesc}
-
-\begin{datadesc}{Py_TPFLAGS_HAVE_GETCHARBUFFER}
- Flag bit set in the type structure to indicate that the
- \member{bf_getcharbuffer} slot is known. This being set does not
- indicate that the object supports the buffer interface or that the
- \member{bf_getcharbuffer} slot is non-\NULL.
-\end{datadesc}
-
-\begin{ctypedesc}[getreadbufferproc]{int (*getreadbufferproc)
- (PyObject *self, int segment, void **ptrptr)}
- Return a pointer to a readable segment of the buffer. This function
- is allowed to raise an exception, in which case it must return
- \code{-1}. The \var{segment} which is passed must be zero or
- positive, and strictly less than the number of segments returned by
- the \member{bf_getsegcount} slot function. On success, it returns
- the length of the buffer memory, and sets \code{*\var{ptrptr}} to a
- pointer to that memory.
-\end{ctypedesc}
-
-\begin{ctypedesc}[getwritebufferproc]{int (*getwritebufferproc)
- (PyObject *self, int segment, void **ptrptr)}
- Return a pointer to a writable memory buffer in
- \code{*\var{ptrptr}}, and the length of that segment as the function
- return value. The memory buffer must correspond to buffer segment
- \var{segment}. Must return \code{-1} and set an exception on
- error. \exception{TypeError} should be raised if the object only
- supports read-only buffers, and \exception{SystemError} should be
- raised when \var{segment} specifies a segment that doesn't exist.
-% Why doesn't it raise ValueError for this one?
-% GJS: because you shouldn't be calling it with an invalid
-% segment. That indicates a blatant programming error in the C
-% code.
-\end{ctypedesc}
-
-\begin{ctypedesc}[getsegcountproc]{int (*getsegcountproc)
- (PyObject *self, int *lenp)}
- Return the number of memory segments which comprise the buffer. If
- \var{lenp} is not \NULL, the implementation must report the sum of
- the sizes (in bytes) of all segments in \code{*\var{lenp}}.
- The function cannot fail.
-\end{ctypedesc}
-
-\begin{ctypedesc}[getcharbufferproc]{int (*getcharbufferproc)
- (PyObject *self, int segment, const char **ptrptr)}
- Return the size of the memory buffer in \var{ptrptr} for segment
- \var{segment}. \code{*\var{ptrptr}} is set to the memory buffer.
-\end{ctypedesc}
-
-
-\section{Supporting the Iterator Protocol
- \label{supporting-iteration}}
-
-
-\section{Supporting Cyclic Garbarge Collection
- \label{supporting-cycle-detection}}
-
-Python's support for detecting and collecting garbage which involves
-circular references requires support from object types which are
-``containers'' for other objects which may also be containers. Types
-which do not store references to other objects, or which only store
-references to atomic types (such as numbers or strings), do not need
-to provide any explicit support for garbage collection.
-
-An example showing the use of these interfaces can be found in
-``\ulink{Supporting the Cycle
-Collector}{../ext/example-cycle-support.html}'' in
-\citetitle[../ext/ext.html]{Extending and Embedding the Python
-Interpreter}.
-
-To create a container type, the \member{tp_flags} field of the type
-object must include the \constant{Py_TPFLAGS_HAVE_GC} and provide an
-implementation of the \member{tp_traverse} handler. If instances of the
-type are mutable, a \member{tp_clear} implementation must also be
-provided.
-
-\begin{datadesc}{Py_TPFLAGS_HAVE_GC}
- Objects with a type with this flag set must conform with the rules
- documented here. For convenience these objects will be referred to
- as container objects.
-\end{datadesc}
-
-Constructors for container types must conform to two rules:
-
-\begin{enumerate}
-\item The memory for the object must be allocated using
- \cfunction{PyObject_GC_New()} or \cfunction{PyObject_GC_VarNew()}.
-
-\item Once all the fields which may contain references to other
- containers are initialized, it must call
- \cfunction{PyObject_GC_Track()}.
-\end{enumerate}
-
-\begin{cfuncdesc}{\var{TYPE}*}{PyObject_GC_New}{TYPE, PyTypeObject *type}
- Analogous to \cfunction{PyObject_New()} but for container objects with
- the \constant{Py_TPFLAGS_HAVE_GC} flag set.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{\var{TYPE}*}{PyObject_GC_NewVar}{TYPE, PyTypeObject *type,
- int size}
- Analogous to \cfunction{PyObject_NewVar()} but for container objects
- with the \constant{Py_TPFLAGS_HAVE_GC} flag set.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyVarObject *}{PyObject_GC_Resize}{PyVarObject *op, int}
- Resize an object allocated by \cfunction{PyObject_NewVar()}. Returns
- the resized object or \NULL{} on failure.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyObject_GC_Track}{PyObject *op}
- Adds the object \var{op} to the set of container objects tracked by
- the collector. The collector can run at unexpected times so objects
- must be valid while being tracked. This should be called once all
- the fields followed by the \member{tp_traverse} handler become valid,
- usually near the end of the constructor.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{_PyObject_GC_TRACK}{PyObject *op}
- A macro version of \cfunction{PyObject_GC_Track()}. It should not be
- used for extension modules.
-\end{cfuncdesc}
-
-Similarly, the deallocator for the object must conform to a similar
-pair of rules:
-
-\begin{enumerate}
-\item Before fields which refer to other containers are invalidated,
- \cfunction{PyObject_GC_UnTrack()} must be called.
-
-\item The object's memory must be deallocated using
- \cfunction{PyObject_GC_Del()}.
-\end{enumerate}
-
-\begin{cfuncdesc}{void}{PyObject_GC_Del}{PyObject *op}
- Releases memory allocated to an object using
- \cfunction{PyObject_GC_New()} or \cfunction{PyObject_GC_NewVar()}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyObject_GC_UnTrack}{PyObject *op}
- Remove the object \var{op} from the set of container objects tracked
- by the collector. Note that \cfunction{PyObject_GC_Track()} can be
- called again on this object to add it back to the set of tracked
- objects. The deallocator (\member{tp_dealloc} handler) should call
- this for the object before any of the fields used by the
- \member{tp_traverse} handler become invalid.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{_PyObject_GC_UNTRACK}{PyObject *op}
- A macro version of \cfunction{PyObject_GC_UnTrack()}. It should not be
- used for extension modules.
-\end{cfuncdesc}
-
-The \member{tp_traverse} handler accepts a function parameter of this
-type:
-
-\begin{ctypedesc}[visitproc]{int (*visitproc)(PyObject *object, void *arg)}
- Type of the visitor function passed to the \member{tp_traverse}
- handler. The function should be called with an object to traverse
- as \var{object} and the third parameter to the \member{tp_traverse}
- handler as \var{arg}.
-\end{ctypedesc}
-
-The \member{tp_traverse} handler must have the following type:
-
-\begin{ctypedesc}[traverseproc]{int (*traverseproc)(PyObject *self,
- visitproc visit, void *arg)}
- Traversal function for a container object. Implementations must
- call the \var{visit} function for each object directly contained by
- \var{self}, with the parameters to \var{visit} being the contained
- object and the \var{arg} value passed to the handler. If
- \var{visit} returns a non-zero value then an error has occurred and
- that value should be returned immediately.
-\end{ctypedesc}
-
-The \member{tp_clear} handler must be of the \ctype{inquiry} type, or
-\NULL{} if the object is immutable.
-
-\begin{ctypedesc}[inquiry]{int (*inquiry)(PyObject *self)}
- Drop references that may have created reference cycles. Immutable
- objects do not have to define this method since they can never
- directly create reference cycles. Note that the object must still
- be valid after calling this method (don't just call
- \cfunction{Py_DECREF()} on a reference). The collector will call
- this method if it detects that this object is involved in a
- reference cycle.
-\end{ctypedesc}
diff --git a/Doc/api/refcounting.tex b/Doc/api/refcounting.tex
deleted file mode 100644
index 03530f09a9..0000000000
--- a/Doc/api/refcounting.tex
+++ /dev/null
@@ -1,48 +0,0 @@
-\chapter{Reference Counting \label{countingRefs}}
-
-
-The macros in this section are used for managing reference counts
-of Python objects.
-
-
-\begin{cfuncdesc}{void}{Py_INCREF}{PyObject *o}
- Increment the reference count for object \var{o}. The object must
- not be \NULL; if you aren't sure that it isn't \NULL, use
- \cfunction{Py_XINCREF()}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{Py_XINCREF}{PyObject *o}
- Increment the reference count for object \var{o}. The object may be
- \NULL, in which case the macro has no effect.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{Py_DECREF}{PyObject *o}
- Decrement the reference count for object \var{o}. The object must
- not be \NULL; if you aren't sure that it isn't \NULL, use
- \cfunction{Py_XDECREF()}. If the reference count reaches zero, the
- object's type's deallocation function (which must not be \NULL) is
- invoked.
-
- \warning{The deallocation function can cause arbitrary Python code
- to be invoked (e.g. when a class instance with a \method{__del__()}
- method is deallocated). While exceptions in such code are not
- propagated, the executed code has free access to all Python global
- variables. This means that any object that is reachable from a
- global variable should be in a consistent state before
- \cfunction{Py_DECREF()} is invoked. For example, code to delete an
- object from a list should copy a reference to the deleted object in
- a temporary variable, update the list data structure, and then call
- \cfunction{Py_DECREF()} for the temporary variable.}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{Py_XDECREF}{PyObject *o}
- Decrement the reference count for object \var{o}. The object may be
- \NULL, in which case the macro has no effect; otherwise the effect
- is the same as for \cfunction{Py_DECREF()}, and the same warning
- applies.
-\end{cfuncdesc}
-
-The following functions or macros are only for use within the
-interpreter core: \cfunction{_Py_Dealloc()},
-\cfunction{_Py_ForgetReference()}, \cfunction{_Py_NewReference()}, as
-well as the global variable \cdata{_Py_RefTotal}.
diff --git a/Doc/api/refcounts.dat b/Doc/api/refcounts.dat
deleted file mode 100644
index 0f2e9b57a8..0000000000
--- a/Doc/api/refcounts.dat
+++ /dev/null
@@ -1,1578 +0,0 @@
-# Created by Skip Montanaro .
-
-# Format:
-# function ':' type ':' [param name] ':' [refcount effect] ':' [comment]
-# If the param name slot is empty, that line corresponds to the function's
-# return value, otherwise it's the type of the named parameter.
-
-# The first line of a function block gives type/refcount information for the
-# function's return value. Successive lines with the same function name
-# correspond to the function's parameter list and appear in the order the
-# parameters appear in the function's prototype.
-
-# For readability, each function's lines are surrounded by a blank line.
-# The blocks are sorted alphabetically by function name.
-
-# Refcount behavior is given for all PyObject* types: 0 (no change), +1
-# (increment) and -1 (decrement). A blank refcount field indicates the
-# parameter or function value is not a PyObject* and is therefore not
-# subject to reference counting. A special case for the value "null"
-# (without quotes) is used for functions which return a PyObject* type but
-# always return NULL. This is used by some of the PyErr_*() functions, in
-# particular.
-
-# XXX NOTE: the 0/+1/-1 refcount information for arguments is
-# confusing! Much more useful would be to indicate whether the
-# function "steals" a reference to the argument or not. Take for
-# example PyList_SetItem(list, i, item). This lists as a 0 change for
-# both the list and the item arguments. However, in fact it steals a
-# reference to the item argument!
-
-# The parameter names are as they appear in the API manual, not the source
-# code.
-
-PyBuffer_FromObject:PyObject*::+1:
-PyBuffer_FromObject:PyObject*:base:+1:
-PyBuffer_FromObject:int:offset::
-PyBuffer_FromObject:int:size::
-
-PyBuffer_FromReadWriteObject:PyObject*::+1:
-PyBuffer_FromReadWriteObject:PyObject*:base:+1:
-PyBuffer_FromReadWriteObject:int:offset::
-PyBuffer_FromReadWriteObject:int:size::
-
-PyBuffer_FromMemory:PyObject*::+1:
-PyBuffer_FromMemory:void*:ptr::
-PyBuffer_FromMemory:int:size::
-
-PyBuffer_FromReadWriteMemory:PyObject*::+1:
-PyBuffer_FromReadWriteMemory:void*:ptr::
-PyBuffer_FromReadWriteMemory:int:size::
-
-PyBuffer_New:PyObject*::+1:
-PyBuffer_New:int:size::
-
-PyCObject_AsVoidPtr:void*:::
-PyCObject_AsVoidPtr:PyObject*:self:0:
-
-PyCObject_FromVoidPtr:PyObject*::+1:
-PyCObject_FromVoidPtr:void*:cobj::
-PyCObject_FromVoidPtr::void (* destr)(void* )::
-
-PyCObject_FromVoidPtrAndDesc:PyObject*::+1:
-PyCObject_FromVoidPtrAndDesc:void*:cobj::
-PyCObject_FromVoidPtrAndDesc:void*:desc::
-PyCObject_FromVoidPtrAndDesc:void(*)(void*,void*):destr::
-
-PyCObject_GetDesc:void*:::
-PyCObject_GetDesc:PyObject*:self:0:
-
-PyCell_New:PyObject*::+1:
-PyCell_New:PyObject*:ob:0:
-
-PyCell_GET:PyObject*::0:
-PyCell_GET:PyObject*:ob:0:
-
-PyCell_Get:PyObject*::+1:
-PyCell_Get:PyObject*:cell:0:
-
-PyCell_SET:void:::
-PyCell_SET:PyObject*:cell:0:
-PyCell_SET:PyObject*:value:0:
-
-PyCell_Set:int:::
-PyCell_Set:PyObject*:cell:0:
-PyCell_Set:PyObject*:value:0:
-
-PyCallIter_New:PyObject*::+1:
-PyCallIter_New:PyObject*:callable::
-PyCallIter_New:PyObject*:sentinel::
-
-PyCallable_Check:int:::
-PyCallable_Check:PyObject*:o:0:
-
-PyComplex_AsCComplex:Py_complex:::
-PyComplex_AsCComplex:PyObject*:op:0:
-
-PyComplex_Check:int:::
-PyComplex_Check:PyObject*:p:0:
-
-PyComplex_FromCComplex:PyObject*::+1:
-PyComplex_FromCComplex::Py_complex v::
-
-PyComplex_FromDoubles:PyObject*::+1:
-PyComplex_FromDoubles::double real::
-PyComplex_FromDoubles::double imag::
-
-PyComplex_ImagAsDouble:double:::
-PyComplex_ImagAsDouble:PyObject*:op:0:
-
-PyComplex_RealAsDouble:double:::
-PyComplex_RealAsDouble:PyObject*:op:0:
-
-PyDescr_NewGetSet:PyObject*::+1:
-PyDescr_NewGetSet:PyTypeObject*:type::
-PyDescr_NewGetSet:PyGetSetDef*:getset::
-
-PyDescr_NewMember:PyObject*::+1:
-PyDescr_NewMember:PyTypeObject*:type::
-PyDescr_NewMember:PyMemberDef*:member::
-
-PyDescr_NewMethod:PyObject*::+1:
-PyDescr_NewMethod:PyTypeObject*:type::
-PyDescr_NewMethod:PyMethodDef*:meth::
-
-PyDescr_NewWrapper:PyObject*::+1:
-PyDescr_NewWrapper:PyTypeObject*:type::
-PyDescr_NewWrapper:struct wrapperbase*:base::
-PyDescr_NewWrapper:void*:wrapped::
-
-PyDict_Check:int:::
-PyDict_Check:PyObject*:p:0:
-
-PyDict_Clear:void:::
-PyDict_Clear:PyObject*:p:0:
-
-PyDict_DelItem:int:::
-PyDict_DelItem:PyObject*:p:0:
-PyDict_DelItem:PyObject*:key:0:
-
-PyDict_DelItemString:int:::
-PyDict_DelItemString:PyObject*:p:0:
-PyDict_DelItemString:char*:key::
-
-PyDict_GetItem:PyObject*::0:0
-PyDict_GetItem:PyObject*:p:0:
-PyDict_GetItem:PyObject*:key:0:
-
-PyDict_GetItemString:PyObject*::0:
-PyDict_GetItemString:PyObject*:p:0:
-PyDict_GetItemString:char*:key::
-
-PyDict_Items:PyObject*::+1:
-PyDict_Items:PyObject*:p:0:
-
-PyDict_Keys:PyObject*::+1:
-PyDict_Keys:PyObject*:p:0:
-
-PyDict_New:PyObject*::+1:
-
-PyDict_Copy:PyObject*::+1:
-PyDict_Copy:PyObject*:p:0:
-
-PyDict_Next:int:::
-PyDict_Next:PyObject*:p:0:
-PyDict_Next:int:ppos::
-PyDict_Next:PyObject**:pkey:0:
-PyDict_Next:PyObject**:pvalue:0:
-
-PyDict_SetItem:int:::
-PyDict_SetItem:PyObject*:p:0:
-PyDict_SetItem:PyObject*:key:+1:
-PyDict_SetItem:PyObject*:val:+1:
-
-PyDict_SetItemString:int:::
-PyDict_SetItemString:PyObject*:p:0:
-PyDict_SetItemString:char*:key::
-PyDict_SetItemString:PyObject*:val:+1:
-
-PyDict_Size:int:::
-PyDict_Size:PyObject*:p::
-
-PyDict_Values:PyObject*::+1:
-PyDict_Values:PyObject*:p:0:
-
-PyDictProxy_New:PyObject*::+1:
-PyDictProxy_New:PyObject*:dict:0:
-
-PyErr_BadArgument:int:::
-
-PyErr_BadInternalCall:void:::
-
-PyErr_CheckSignals:int:::
-
-PyErr_Clear:void:::
-
-PyErr_ExceptionMatches:int:::
-PyErr_ExceptionMatches:PyObject*:exc:0:
-
-PyErr_Fetch:void:::
-PyErr_Fetch:PyObject**:ptype:0:
-PyErr_Fetch:PyObject**:pvalue:0:
-PyErr_Fetch:PyObject**:ptraceback:0:
-
-PyErr_GivenExceptionMatches:int:::
-PyErr_GivenExceptionMatches:PyObject*:given:0:
-PyErr_GivenExceptionMatches:PyObject*:exc:0:
-
-PyErr_NewException:PyObject*::+1:
-PyErr_NewException:char*:name::
-PyErr_NewException:PyObject*:base:0:
-PyErr_NewException:PyObject*:dict:0:
-
-PyErr_NoMemory:PyObject*::null:
-
-PyErr_NormalizeException:void:::
-PyErr_NormalizeException:PyObject**:exc::???
-PyErr_NormalizeException:PyObject**:val::???
-PyErr_NormalizeException:PyObject**:tb::???
-
-PyErr_Occurred:PyObject*::0:
-
-PyErr_Print:void:::
-
-PyErr_Restore:void:::
-PyErr_Restore:PyObject*:type:-1:
-PyErr_Restore:PyObject*:value:-1:
-PyErr_Restore:PyObject*:traceback:-1:
-
-PyErr_SetFromErrno:PyObject*::null:
-PyErr_SetFromErrno:PyObject*:type:0:
-
-PyErr_SetFromErrnoWithFilename:PyObject*::null:
-PyErr_SetFromErrnoWithFilename:PyObject*:type:0:
-PyErr_SetFromErrnoWithFilename:char*:filename::
-
-PyErr_SetFromWindowsErr:PyObject*::null:
-PyErr_SetFromWindowsErr:int:ierr::
-
-PyErr_SetFromWindowsErrWithFilename:PyObject*::null:
-PyErr_SetFromWindowsErrWithFilename:int:ierr::
-PyErr_SetFromWindowsErrWithFilename:char*:filename::
-
-PyErr_SetInterrupt:void:::
-
-PyErr_SetNone:void:::
-PyErr_SetNone:PyObject*:type:+1:
-
-PyErr_SetObject:void:::
-PyErr_SetObject:PyObject*:type:+1:
-PyErr_SetObject:PyObject*:value:+1:
-
-PyErr_SetString:void:::
-PyErr_SetString:PyObject*:type:+1:
-PyErr_SetString:char*:message::
-
-PyErr_Format:PyObject*::null:
-PyErr_Format:PyObject*:exception:+1:
-PyErr_Format:char*:format::
-PyErr_Format::...::
-
-PyErr_Warn:int:::
-PyErr_Warn:PyObject*:category:0:
-PyErr_Warn:char*:message::
-
-PyEval_AcquireLock:void:::
-
-PyEval_AcquireThread:void:::
-PyEval_AcquireThread:PyThreadState*:tstate::
-
-PyEval_InitThreads:void:::
-
-PyEval_ReleaseLock:void:::
-
-PyEval_ReleaseThread:void:::
-PyEval_ReleaseThread:PyThreadState*:tstate::
-
-PyEval_RestoreThread:void:::
-PyEval_RestoreThread:PyThreadState*:tstate::
-
-PyEval_SaveThread:PyThreadState*:::
-
-PyEval_EvalCode:PyObject*::+1:
-PyEval_EvalCode:PyCodeObject*:co:0:
-PyEval_EvalCode:PyObject*:globals:0:
-PyEval_EvalCode:PyObject*:locals:0:
-
-PyFile_AsFile:FILE*:::
-PyFile_AsFile:PyFileObject*:p:0:
-
-PyFile_Check:int:::
-PyFile_Check:PyObject*:p:0:
-
-PyFile_FromFile:PyObject*::+1:
-PyFile_FromFile:FILE*:fp::
-PyFile_FromFile:char*:name::
-PyFile_FromFile:char*:mode::
-PyFile_FromFile:int(*:close)::
-
-PyFile_FromString:PyObject*::+1:
-PyFile_FromString:char*:name::
-PyFile_FromString:char*:mode::
-
-PyFile_GetLine:PyObject*::+1:
-PyFile_GetLine:PyObject*:p::
-PyFile_GetLine:int:n::
-
-PyFile_Name:PyObject*::0:
-PyFile_Name:PyObject*:p:0:
-
-PyFile_SetBufSize:void:::
-PyFile_SetBufSize:PyFileObject*:p:0:
-PyFile_SetBufSize:int:n::
-
-PyFile_SoftSpace:int:::
-PyFile_SoftSpace:PyFileObject*:p:0:
-PyFile_SoftSpace:int:newflag::
-
-PyFile_WriteObject:int:::
-PyFile_WriteObject:PyObject*:obj:0:
-PyFile_WriteObject:PyFileObject*:p:0:
-PyFile_WriteObject:int:flags::
-
-PyFile_WriteString:int:::
-PyFile_WriteString:const char*:s::
-PyFile_WriteString:PyFileObject*:p:0:
-PyFile_WriteString:int:flags::
-
-PyFloat_AS_DOUBLE:double:::
-PyFloat_AS_DOUBLE:PyObject*:pyfloat:0:
-
-PyFloat_AsDouble:double:::
-PyFloat_AsDouble:PyObject*:pyfloat:0:
-
-PyFloat_Check:int:::
-PyFloat_Check:PyObject*:p:0:
-
-PyFloat_FromDouble:PyObject*::+1:
-PyFloat_FromDouble:double:v::
-
-Py_InitModule:PyObject*::0:
-Py_InitModule:name:char*::
-Py_InitModule:methods:PyMethodDef[]::
-
-Py_InitModule3:PyObject*::0:
-Py_InitModule3:name:char*::
-Py_InitModule3:methods:PyMethodDef[]::
-Py_InitModule3:doc:char*::
-
-Py_InitModule4:PyObject*::0:
-Py_InitModule4:name:char*::
-Py_InitModule4:methods:PyMethodDef[]::
-Py_InitModule4:doc:char*::
-Py_InitModule4:self:PyObject*::
-Py_InitModule4:apiver:int::usually provided by Py_InitModule or Py_InitModule3
-
-PyImport_AddModule:PyObject*::0:reference borrowed from sys.modules
-PyImport_AddModule:char*:name::
-
-PyImport_Cleanup:void:::
-
-PyImport_ExecCodeModule:PyObject*::+1:
-PyImport_ExecCodeModule:char*:name::
-PyImport_ExecCodeModule:PyObject*:co:0:
-
-PyImport_GetMagicNumber:long:::
-
-PyImport_GetModuleDict:PyObject*::0:
-
-PyImport_Import:PyObject*::+1:
-PyImport_Import:PyObject*:name:0:
-
-PyImport_ImportFrozenModule:int:::
-PyImport_ImportFrozenModule:char*:::
-
-PyImport_ImportModule:PyObject*::+1:
-PyImport_ImportModule:char*:name::
-
-PyImport_ImportModuleEx:PyObject*::+1:
-PyImport_ImportModuleEx:char*:name::
-PyImport_ImportModuleEx:PyObject*:globals:0:???
-PyImport_ImportModuleEx:PyObject*:locals:0:???
-PyImport_ImportModuleEx:PyObject*:fromlist:0:???
-
-PyImport_ReloadModule:PyObject*::+1:
-PyImport_ReloadModule:PyObject*:m:0:
-
-PyInstance_New:PyObject*::+1:
-PyInstance_New:PyObject*:klass:+1:
-PyInstance_New:PyObject*:arg:0:
-PyInstance_New:PyObject*:kw:0:
-
-PyInstance_NewRaw:PyObject*::+1:
-PyInstance_NewRaw:PyObject*:klass:+1:
-PyInstance_NewRaw:PyObject*:dict:+1:
-
-PyInt_AS_LONG:long:::
-PyInt_AS_LONG:PyIntObject*:io:0:
-
-PyInt_AsLong:long:::
-PyInt_AsLong:PyObject*:io:0:
-
-PyInt_Check:int:::
-PyInt_Check:PyObject*:op:0:
-
-PyInt_FromLong:PyObject*::+1:
-PyInt_FromLong:long:ival::
-
-PyInt_GetMax:long:::
-
-PyInterpreterState_Clear:void:::
-PyInterpreterState_Clear:PyInterpreterState*:interp::
-
-PyInterpreterState_Delete:void:::
-PyInterpreterState_Delete:PyInterpreterState*:interp::
-
-PyInterpreterState_New:PyInterpreterState*:::
-
-PyIter_Check:int:o:0:
-
-PyIter_Next:PyObject*::+1:
-PyIter_Next:PyObject*:o:0:
-
-PyList_Append:int:::
-PyList_Append:PyObject*:list:0:
-PyList_Append:PyObject*:item:+1:
-
-PyList_AsTuple:PyObject*::+1:
-PyList_AsTuple:PyObject*:list:0:
-
-PyList_Check:int:::
-PyList_Check:PyObject*:p:0:
-
-PyList_GET_ITEM:PyObject*::0:
-PyList_GET_ITEM:PyObject*:list:0:
-PyList_GET_ITEM:int:i:0:
-
-PyList_GET_SIZE:int:::
-PyList_GET_SIZE:PyObject*:list:0:
-
-PyList_GetItem:PyObject*::0:
-PyList_GetItem:PyObject*:list:0:
-PyList_GetItem:int:index::
-
-PyList_GetSlice:PyObject*::+1:
-PyList_GetSlice:PyObject*:list:0:
-PyList_GetSlice:int:low::
-PyList_GetSlice:int:high::
-
-PyList_Insert:int:::
-PyList_Insert:PyObject*:list:0:
-PyList_Insert:int:index::
-PyList_Insert:PyObject*:item:+1:
-
-PyList_New:PyObject*::+1:
-PyList_New:int:len::
-
-PyList_Reverse:int:::
-PyList_Reverse:PyObject*:list:0:
-
-PyList_SET_ITEM:void:::
-PyList_SET_ITEM:PyObject*:list:0:
-PyList_SET_ITEM:int:i::
-PyList_SET_ITEM:PyObject*:o:0:
-
-PyList_SetItem:int:::
-PyList_SetItem:PyObject*:list:0:
-PyList_SetItem:int:index::
-PyList_SetItem:PyObject*:item:0:
-
-PyList_SetSlice:int:::
-PyList_SetSlice:PyObject*:list:0:
-PyList_SetSlice:int:low::
-PyList_SetSlice:int:high::
-PyList_SetSlice:PyObject*:itemlist:0:but increfs its elements?
-
-PyList_Size:int:::
-PyList_Size:PyObject*:list:0:
-
-PyList_Sort:int:::
-PyList_Sort:PyObject*:list:0:
-
-PyLong_AsDouble:double:::
-PyLong_AsDouble:PyObject*:pylong:0:
-
-PyLong_AsLong:long:::
-PyLong_AsLong:PyObject*:pylong:0:
-
-PyLong_AsUnsignedLong:unsigned long:::
-PyLong_AsUnsignedLong:PyObject*:pylong:0:
-
-PyLong_Check:int:::
-PyLong_Check:PyObject*:p:0:
-
-PyLong_FromDouble:PyObject*::+1:
-PyLong_FromDouble:double:v::
-
-PyLong_FromLong:PyObject*::+1:
-PyLong_FromLong:long:v::
-
-PyLong_FromLongLong:PyObject*::+1:
-PyLong_FromLongLong:long long:v::
-
-PyLong_FromUnsignedLongLong:PyObject*::+1:
-PyLong_FromUnsignedLongLong:unsigned long long:v::
-
-PyLong_FromString:PyObject*::+1:
-PyLong_FromString:char*:str::
-PyLong_FromString:char**:pend::
-PyLong_FromString:int:base::
-
-PyLong_FromUnicode:PyObject*::+1:
-PyLong_FromUnicode:Py_UNICODE:u::
-PyLong_FromUnicode:int:length::
-PyLong_FromUnicode:int:base::
-
-PyLong_FromUnsignedLong:PyObject*::+1:
-PyLong_FromUnsignedLong:unsignedlong:v::
-
-PyLong_FromVoidPtr:PyObject*::+1:
-PyLong_FromVoidPtr:void*:p::
-
-PyMapping_Check:int:::
-PyMapping_Check:PyObject*:o:0:
-
-PyMapping_DelItem:int:::
-PyMapping_DelItem:PyObject*:o:0:
-PyMapping_DelItem:PyObject*:key:0:
-
-PyMapping_DelItemString:int:::
-PyMapping_DelItemString:PyObject*:o:0:
-PyMapping_DelItemString:char*:key::
-
-PyMapping_GetItemString:PyObject*::+1:
-PyMapping_GetItemString:PyObject*:o:0:
-PyMapping_GetItemString:char*:key::
-
-PyMapping_HasKey:int:::
-PyMapping_HasKey:PyObject*:o:0:
-PyMapping_HasKey:PyObject*:key::
-
-PyMapping_HasKeyString:int:::
-PyMapping_HasKeyString:PyObject*:o:0:
-PyMapping_HasKeyString:char*:key::
-
-PyMapping_Items:PyObject*::+1:
-PyMapping_Items:PyObject*:o:0:
-
-PyMapping_Keys:PyObject*::+1:
-PyMapping_Keys:PyObject*:o:0:
-
-PyMapping_Length:int:::
-PyMapping_Length:PyObject*:o:0:
-
-PyMapping_SetItemString:int:::
-PyMapping_SetItemString:PyObject*:o:0:
-PyMapping_SetItemString:char*:key::
-PyMapping_SetItemString:PyObject*:v:+1:
-
-PyMapping_Values:PyObject*::+1:
-PyMapping_Values:PyObject*:o:0:
-
-PyMarshal_ReadLastObjectFromFile:PyObject*::+1:
-PyMarshal_ReadLastObjectFromFile:FILE*:file::
-
-PyMarshal_ReadObjectFromFile:PyObject*::+1:
-PyMarshal_ReadObjectFromFile:FILE*:file::
-
-PyMarshal_ReadObjectFromString:PyObject*::+1:
-PyMarshal_ReadObjectFromString:char*:string::
-PyMarshal_ReadObjectFromString:int:len::
-
-PyMarshal_WriteObjectToString:PyObject*::+1:
-PyMarshal_WriteObjectToString:PyObject*:value:0:
-
-PyMethod_Class:PyObject*::0:
-PyMethod_Class:PyObject*:im:0:
-
-PyMethod_Function:PyObject*::0:
-PyMethod_Function:PyObject*:im:0:
-
-PyMethod_GET_CLASS:PyObject*::0:
-PyMethod_GET_CLASS:PyObject*:im:0:
-
-PyMethod_GET_FUNCTION:PyObject*::0:
-PyMethod_GET_FUNCTION:PyObject*:im:0:
-
-PyMethod_GET_SELF:PyObject*::0:
-PyMethod_GET_SELF:PyObject*:im:0:
-
-PyMethod_New:PyObject*::+1:
-PyMethod_New:PyObject*:func:0:
-PyMethod_New:PyObject*:self:0:
-PyMethod_New:PyObject*:class:0:
-
-PyMethod_Self:PyObject*::0:
-PyMethod_Self:PyObject*:im:0:
-
-PyModule_GetDict:PyObject*::0:
-PyModule_GetDict::PyObject* module:0:
-
-PyModule_GetFilename:char*:::
-PyModule_GetFilename:PyObject*:module:0:
-
-PyModule_GetName:char*:::
-PyModule_GetName:PyObject*:module:0:
-
-PyModule_New:PyObject*::+1:
-PyModule_New::char* name::
-
-PyNumber_Absolute:PyObject*::+1:
-PyNumber_Absolute:PyObject*:o:0:
-
-PyNumber_Add:PyObject*::+1:
-PyNumber_Add:PyObject*:o1:0:
-PyNumber_Add:PyObject*:o2:0:
-
-PyNumber_And:PyObject*::+1:
-PyNumber_And:PyObject*:o1:0:
-PyNumber_And:PyObject*:o2:0:
-
-PyNumber_Check:PyObject*:o:0:
-PyNumber_Check:int:::
-
-PyNumber_Coerce:int:::
-PyNumber_Coerce:PyObject**:p1:+1:
-PyNumber_Coerce:PyObject**:p2:+1:
-
-PyNumber_Divide:PyObject*::+1:
-PyNumber_Divide:PyObject*:o1:0:
-PyNumber_Divide:PyObject*:o2:0:
-
-PyNumber_Divmod:PyObject*::+1:
-PyNumber_Divmod:PyObject*:o1:0:
-PyNumber_Divmod:PyObject*:o2:0:
-
-PyNumber_Float:PyObject*::+1:
-PyNumber_Float:PyObject*:o:0:
-
-PyNumber_FloorDivide:PyObject*::+1:
-PyNumber_FloorDivide:PyObject*:v:0:
-PyNumber_FloorDivide:PyObject*:w:0:
-
-PyNumber_InPlaceAdd:PyObject*::+1:
-PyNumber_InPlaceAdd:PyObject*:v:0:
-PyNumber_InPlaceAdd:PyObject*:w:0:
-
-PyNumber_InPlaceAnd:PyObject*::+1:
-PyNumber_InPlaceAnd:PyObject*:v:0:
-PyNumber_InPlaceAnd:PyObject*:w:0:
-
-PyNumber_InPlaceDivide:PyObject*::+1:
-PyNumber_InPlaceDivide:PyObject*:v:0:
-PyNumber_InPlaceDivide:PyObject*:w:0:
-
-PyNumber_InPlaceFloorDivide:PyObject*::+1:
-PyNumber_InPlaceFloorDivide:PyObject*:v:0:
-PyNumber_InPlaceFloorDivide:PyObject*:w:0:
-
-PyNumber_InPlaceLshift:PyObject*::+1:
-PyNumber_InPlaceLshift:PyObject*:v:0:
-PyNumber_InPlaceLshift:PyObject*:w:0:
-
-PyNumber_InPlaceMultiply:PyObject*::+1:
-PyNumber_InPlaceMultiply:PyObject*:v:0:
-PyNumber_InPlaceMultiply:PyObject*:w:0:
-
-PyNumber_InPlaceOr:PyObject*::+1:
-PyNumber_InPlaceOr:PyObject*:v:0:
-PyNumber_InPlaceOr:PyObject*:w:0:
-
-PyNumber_InPlacePower:PyObject*::+1:
-PyNumber_InPlacePower:PyObject*:v:0:
-PyNumber_InPlacePower:PyObject*:w:0:
-PyNumber_InPlacePower:PyObject*:z:0:
-
-PyNumber_InPlaceRemainder:PyObject*::+1:
-PyNumber_InPlaceRemainder:PyObject*:v:0:
-PyNumber_InPlaceRemainder:PyObject*:w:0:
-
-PyNumber_InPlaceRshift:PyObject*::+1:
-PyNumber_InPlaceRshift:PyObject*:v:0:
-PyNumber_InPlaceRshift:PyObject*:w:0:
-
-PyNumber_InPlaceSubtract:PyObject*::+1:
-PyNumber_InPlaceSubtract:PyObject*:v:0:
-PyNumber_InPlaceSubtract:PyObject*:w:0:
-
-PyNumber_InPlaceTrueDivide:PyObject*::+1:
-PyNumber_InPlaceTrueDivide:PyObject*:v:0:
-PyNumber_InPlaceTrueDivide:PyObject*:w:0:
-
-PyNumber_InPlaceXor:PyObject*::+1:
-PyNumber_InPlaceXor:PyObject*:v:0:
-PyNumber_InPlaceXor:PyObject*:w:0:
-
-PyNumber_Int:PyObject*::+1:
-PyNumber_Int:PyObject*:o:0:
-
-PyNumber_Invert:PyObject*::+1:
-PyNumber_Invert:PyObject*:o:0:
-
-PyNumber_Long:PyObject*::+1:
-PyNumber_Long:PyObject*:o:0:
-
-PyNumber_Lshift:PyObject*::+1:
-PyNumber_Lshift:PyObject*:o1:0:
-PyNumber_Lshift:PyObject*:o2:0:
-
-PyNumber_Multiply:PyObject*::+1:
-PyNumber_Multiply:PyObject*:o1:0:
-PyNumber_Multiply:PyObject*:o2:0:
-
-PyNumber_Negative:PyObject*::+1:
-PyNumber_Negative:PyObject*:o:0:
-
-PyNumber_Or:PyObject*::+1:
-PyNumber_Or:PyObject*:o1:0:
-PyNumber_Or:PyObject*:o2:0:
-
-PyNumber_Positive:PyObject*::+1:
-PyNumber_Positive:PyObject*:o:0:
-
-PyNumber_Power:PyObject*::+1:
-PyNumber_Power:PyObject*:o1:0:
-PyNumber_Power:PyObject*:o2:0:
-PyNumber_Power:PyObject*:o3:0:
-
-PyNumber_Remainder:PyObject*::+1:
-PyNumber_Remainder:PyObject*:o1:0:
-PyNumber_Remainder:PyObject*:o2:0:
-
-PyNumber_Rshift:PyObject*::+1:
-PyNumber_Rshift:PyObject*:o1:0:
-PyNumber_Rshift:PyObject*:o2:0:
-
-PyNumber_Subtract:PyObject*::+1:
-PyNumber_Subtract:PyObject*:o1:0:
-PyNumber_Subtract:PyObject*:o2:0:
-
-PyNumber_TrueDivide:PyObject*::+1:
-PyNumber_TrueDivide:PyObject*:v:0:
-PyNumber_TrueDivide:PyObject*:w:0:
-
-PyNumber_Xor:PyObject*::+1:
-PyNumber_Xor:PyObject*:o1:0:
-PyNumber_Xor:PyObject*:o2:0:
-
-PyOS_GetLastModificationTime:long:::
-PyOS_GetLastModificationTime:char*:filename::
-
-PyObject_AsFileDescriptor:int:::
-PyObject_AsFileDescriptor:PyObject*:o:0:
-
-PyObject_CallFunction:PyObject*::+1:
-PyObject_CallFunction:PyObject*:callable_object:0:
-PyObject_CallFunction:char*:format::
-PyObject_CallFunction::...::
-
-PyObject_CallFunctionObjArgs:PyObject*::+1:
-PyObject_CallFunctionObjArgs:PyObject*:callable:0:
-PyObject_CallFunctionObjArgs::...::
-
-PyObject_CallMethod:PyObject*::+1:
-PyObject_CallMethod:PyObject*:o:0:
-PyObject_CallMethod:char*:m::
-PyObject_CallMethod:char*:format::
-PyObject_CallMethod::...::
-
-PyObject_CallMethodObjArgs:PyObject*::+1:
-PyObject_CallMethodObjArgs:PyObject*:o:0:
-PyObject_CallMethodObjArgs:char*:name::
-PyObject_CallMethodObjArgs::...::
-
-PyObject_CallObject:PyObject*::+1:
-PyObject_CallObject:PyObject*:callable_object:0:
-PyObject_CallObject:PyObject*:args:0:
-
-PyObject_Cmp:int:::
-PyObject_Cmp:PyObject*:o1:0:
-PyObject_Cmp:PyObject*:o2:0:
-PyObject_Cmp:int*:result::
-
-PyObject_Compare:int:::
-PyObject_Compare:PyObject*:o1:0:
-PyObject_Compare:PyObject*:o2:0:
-
-PyObject_DelAttr:int:::
-PyObject_DelAttr:PyObject*:o:0:
-PyObject_DelAttr:PyObject*:attr_name:0:
-
-PyObject_DelAttrString:int:::
-PyObject_DelAttrString:PyObject*:o:0:
-PyObject_DelAttrString:char*:attr_name::
-
-PyObject_DelItem:int:::
-PyObject_DelItem:PyObject*:o:0:
-PyObject_DelItem:PyObject*:key:0:
-
-PyObject_Dir:PyObject*::+1:
-PyObject_Dir:PyObject*:o:0:
-
-PyObject_GetAttr:PyObject*::+1:
-PyObject_GetAttr:PyObject*:o:0:
-PyObject_GetAttr:PyObject*:attr_name:0:
-
-PyObject_GetAttrString:PyObject*::+1:
-PyObject_GetAttrString:PyObject*:o:0:
-PyObject_GetAttrString:char*:attr_name::
-
-PyObject_GetItem:PyObject*::+1:
-PyObject_GetItem:PyObject*:o:0:
-PyObject_GetItem:PyObject*:key:0:
-
-PyObject_GetIter:PyObject*::+1:
-PyObject_GetIter:PyObject*:o:0:
-
-PyObject_HasAttr:int:::
-PyObject_HasAttr:PyObject*:o:0:
-PyObject_HasAttr:PyObject*:attr_name:0:
-
-PyObject_HasAttrString:int:::
-PyObject_HasAttrString:PyObject*:o:0:
-PyObject_HasAttrString:char*:attr_name:0:
-
-PyObject_Hash:int:::
-PyObject_Hash:PyObject*:o:0:
-
-PyObject_IsTrue:int:::
-PyObject_IsTrue:PyObject*:o:0:
-
-PyObject_Init:PyObject*::0:
-PyObject_Init:PyObject*:op:0:
-
-PyObject_InitVar:PyVarObject*::0:
-PyObject_InitVar:PyVarObject*:op:0:
-
-PyObject_Length:int:::
-PyObject_Length:PyObject*:o:0:
-
-PyObject_NEW:PyObject*::+1:
-
-PyObject_New:PyObject*::+1:
-
-PyObject_NEW_VAR:PyObject*::+1:
-
-PyObject_NewVar:PyObject*::+1:
-
-PyObject_Print:int:::
-PyObject_Print:PyObject*:o:0:
-PyObject_Print:FILE*:fp::
-PyObject_Print:int:flags::
-
-PyObject_Repr:PyObject*::+1:
-PyObject_Repr:PyObject*:o:0:
-
-PyObject_RichCompare:PyObject*::+1:
-PyObject_RichCompare:PyObject*:o1:0:
-PyObject_RichCompare:PyObject*:o2:0:
-PyObject_RichCompare:int:opid::
-
-PyObject_RichCompareBool:int:::
-PyObject_RichCompareBool:PyObject*:o1:0:
-PyObject_RichCompareBool:PyObject*:o2:0:
-PyObject_RichCompareBool:int:opid::
-
-PyObject_SetAttr:int:::
-PyObject_SetAttr:PyObject*:o:0:
-PyObject_SetAttr:PyObject*:attr_name:0:
-PyObject_SetAttr:PyObject*:v:+1:
-
-PyObject_SetAttrString:int:::
-PyObject_SetAttrString:PyObject*:o:0:
-PyObject_SetAttrString:char*:attr_name::
-PyObject_SetAttrString:PyObject*:v:+1:
-
-PyObject_SetItem:int:::
-PyObject_SetItem:PyObject*:o:0:
-PyObject_SetItem:PyObject*:key:0:
-PyObject_SetItem:PyObject*:v:+1:
-
-PyObject_Str:PyObject*::+1:
-PyObject_Str:PyObject*:o:0:
-
-PyObject_Type:PyObject*::+1:
-PyObject_Type:PyObject*:o:0:
-
-PyObject_Unicode:PyObject*::+1:
-PyObject_Unicode:PyObject*:o:0:
-
-PyParser_SimpleParseFile:struct _node*:::
-PyParser_SimpleParseFile:FILE*:fp::
-PyParser_SimpleParseFile:char*:filename::
-PyParser_SimpleParseFile:int:start::
-
-PyParser_SimpleParseString:struct _node*:::
-PyParser_SimpleParseString:char*:str::
-PyParser_SimpleParseString:int:start::
-
-PyRun_AnyFile:int:::
-PyRun_AnyFile:FILE*:fp::
-PyRun_AnyFile:char*:filename::
-
-PyRun_File:PyObject*::+1:??? -- same as eval_code2()
-PyRun_File:FILE*:fp::
-PyRun_File:char*:filename::
-PyRun_File:int:start::
-PyRun_File:PyObject*:globals:0:
-PyRun_File:PyObject*:locals:0:
-
-PyRun_InteractiveLoop:int:::
-PyRun_InteractiveLoop:FILE*:fp::
-PyRun_InteractiveLoop:char*:filename::
-
-PyRun_InteractiveOne:int:::
-PyRun_InteractiveOne:FILE*:fp::
-PyRun_InteractiveOne:char*:filename::
-
-PyRun_SimpleFile:int:::
-PyRun_SimpleFile:FILE*:fp::
-PyRun_SimpleFile:char*:filename::
-
-PyRun_SimpleString:int:::
-PyRun_SimpleString:char*:command::
-
-PyRun_String:PyObject*::+1:??? -- same as eval_code2()
-PyRun_String:char*:str::
-PyRun_String:int:start::
-PyRun_String:PyObject*:globals:0:
-PyRun_String:PyObject*:locals:0:
-
-PySeqIter_New:PyObject*::+1:
-PySeqIter_New:PyObject*:seq::
-
-PySequence_Check:int:::
-PySequence_Check:PyObject*:o:0:
-
-PySequence_Concat:PyObject*::+1:
-PySequence_Concat:PyObject*:o1:0:
-PySequence_Concat:PyObject*:o2:0:
-
-PySequence_Count:int:::
-PySequence_Count:PyObject*:o:0:
-PySequence_Count:PyObject*:value:0:
-
-PySequence_DelItem:int:::
-PySequence_DelItem:PyObject*:o:0:
-PySequence_DelItem:int:i::
-
-PySequence_DelSlice:int:::
-PySequence_DelSlice:PyObject*:o:0:
-PySequence_DelSlice:int:i1::
-PySequence_DelSlice:int:i2::
-
-PySequence_Fast:PyObject*::+1:
-PySequence_Fast:PyObject*:v:0:
-PySequence_Fast:const char*:m::
-
-PySequence_Fast_GET_ITEM:PyObject*::0:
-PySequence_Fast_GET_ITEM:PyObject*:o:0:
-PySequence_Fast_GET_ITEM:int:i::
-
-PySequence_GetItem:PyObject*::+1:
-PySequence_GetItem:PyObject*:o:0:
-PySequence_GetItem:int:i::
-
-PySequence_GetSlice:PyObject*::+1:
-PySequence_GetSlice:PyObject*:o:0:
-PySequence_GetSlice:int:i1::
-PySequence_GetSlice:int:i2::
-
-PySequence_In:int:::
-PySequence_In:PyObject*:o:0:
-PySequence_In:PyObject*:value:0:
-
-PySequence_Index:int:::
-PySequence_Index:PyObject*:o:0:
-PySequence_Index:PyObject*:value:0:
-
-PySequence_InPlaceConcat:PyObject*::+1:
-PySequence_InPlaceConcat:PyObject*:s:0:
-PySequence_InPlaceConcat:PyObject*:o:0:
-
-PySequence_InPlaceRepeat:PyObject*::+1:
-PySequence_InPlaceRepeat:PyObject*:s:0:
-PySequence_InPlaceRepeat:PyObject*:o:0:
-
-PySequence_ITEM:PyObject*::+1:
-PySequence_ITEM:PyObject*:o:0:
-PySequence_ITEM:int:i::
-
-PySequence_Repeat:PyObject*::+1:
-PySequence_Repeat:PyObject*:o:0:
-PySequence_Repeat:int:count::
-
-PySequence_SetItem:int:::
-PySequence_SetItem:PyObject*:o:0:
-PySequence_SetItem:int:i::
-PySequence_SetItem:PyObject*:v:+1:
-
-PySequence_SetSlice:int:::
-PySequence_SetSlice:PyObject*:o:0:
-PySequence_SetSlice:int:i1::
-PySequence_SetSlice:int:i2::
-PySequence_SetSlice:PyObject*:v:+1:
-
-PySequence_List:PyObject*::+1:
-PySequence_List:PyObject*:o:0:
-
-PySequence_Tuple:PyObject*::+1:
-PySequence_Tuple:PyObject*:o:0:
-
-PySlice_Check:int:::
-PySlice_Check:PyObject*:ob:0:
-
-PySlice_New:PyObject*::+1:
-PySlice_New:PyObject*:start:0:
-PySlice_New:PyObject*:stop:0:
-PySlice_New:PyObject*:step:0:
-
-PyString_AS_STRING:char*:::
-PyString_AS_STRING:PyObject*:string:0:
-
-PyString_AsDecodedObject:PyObject*::+1:
-PyString_AsDecodedObject:PyObject*:str:0:
-PyString_AsDecodedObject:const char*:encoding::
-PyString_AsDecodedObject:const char*:errors::
-
-PyString_AsEncodedObject:PyObject*::+1:
-PyString_AsEncodedObject:PyObject*:str:0:
-PyString_AsEncodedObject:const char*:encoding::
-PyString_AsEncodedObject:const char*:errors::
-
-PyString_AsString:char*:::
-PyString_AsString:PyObject*:string:0:
-
-PyString_AsStringAndSize:int:::
-PyString_AsStringAndSize:PyObject*:obj:0:
-PyString_AsStringAndSize:char**:buffer::
-PyString_AsStringAndSize:int*:length::
-
-PyString_Check:int:::
-PyString_Check:PyObject*:o:0:
-
-PyString_Concat:void:::
-PyString_Concat:PyObject**:string:0:??? -- replaces w/ new string or NULL
-PyString_Concat:PyObject*:newpart:0:
-
-PyString_ConcatAndDel:void:::
-PyString_ConcatAndDel:PyObject**:string:0:??? -- replaces w/ new string or NULL
-PyString_ConcatAndDel:PyObject*:newpart:-1:
-
-PyString_Format:PyObject*::+1:
-PyString_Format:PyObject*:format:0:
-PyString_Format:PyObject*:args:0:
-
-PyString_FromString:PyObject*::+1:
-PyString_FromString:const char*:v::
-
-PyString_FromStringAndSize:PyObject*::+1:
-PyString_FromStringAndSize:const char*:v::
-PyString_FromStringAndSize:int:len::
-
-PyString_FromFormat:PyObject*::+1:
-PyString_FromFormat:const char*:format::
-PyString_FromFormat::...::
-
-PyString_FromFormatV:PyObject*::+1:
-PyString_FromFormatV:const char*:format::
-PyString_FromFormatV:va_list:vargs::
-
-PyString_GET_SIZE:int:::
-PyString_GET_SIZE:PyObject*:string:0:
-
-PyString_InternFromString:PyObject*::+1:
-PyString_InternFromString:const char*:v::
-
-PyString_InternInPlace:void:::
-PyString_InternInPlace:PyObject**:string:+1:???
-
-PyString_Size:int:::
-PyString_Size:PyObject*:string:0:
-
-PyString_Decode:PyObject*::+1:
-PyString_Decode:const char*:s::
-PyString_Decode:int:size::
-PyString_Decode:const char*:encoding::
-PyString_Decode:const char*:errors::
-
-PyString_Encode:PyObject*::+1:
-PyString_Encode:const char*:s::
-PyString_Encode:int:size::
-PyString_Encode:const char*:encoding::
-PyString_Encode:const char*:errors::
-
-PyString_AsEncodedString:PyObject*::+1:
-PyString_AsEncodedString:PyObject*:str::
-PyString_AsEncodedString:const char*:encoding::
-PyString_AsEncodedString:const char*:errors::
-
-PySys_SetArgv:int:::
-PySys_SetArgv:int:argc::
-PySys_SetArgv:char**:argv::
-
-PyThreadState_Clear:void:::
-PyThreadState_Clear:PyThreadState*:tstate::
-
-PyThreadState_Delete:void:::
-PyThreadState_Delete:PyThreadState*:tstate::
-
-PyThreadState_Get:PyThreadState*:::
-
-PyThreadState_GetDict:PyObject*::0:
-
-PyThreadState_New:PyThreadState*:::
-PyThreadState_New:PyInterpreterState*:interp::
-
-PyThreadState_Swap:PyThreadState*:::
-PyThreadState_Swap:PyThreadState*:tstate::
-
-PyTuple_Check:int:::
-PyTuple_Check:PyObject*:p:0:
-
-PyTuple_GET_ITEM:PyObject*::0:
-PyTuple_GET_ITEM:PyTupleObject*:p:0:
-PyTuple_GET_ITEM:int:pos::
-
-PyTuple_GetItem:PyObject*::0:
-PyTuple_GetItem:PyTupleObject*:p:0:
-PyTuple_GetItem:int:pos::
-
-PyTuple_GetSlice:PyObject*::+1:
-PyTuple_GetSlice:PyTupleObject*:p:0:
-PyTuple_GetSlice:int:low::
-PyTuple_GetSlice:int:high::
-
-PyTuple_New:PyObject*::+1:
-PyTuple_New:int:len::
-
-PyTuple_SET_ITEM:void:::
-PyTuple_SET_ITEM:PyTupleObject*:p:0:
-PyTuple_SET_ITEM:int:pos::
-PyTuple_SET_ITEM:PyObject*:o:0:
-
-PyTuple_SetItem:int:::
-PyTuple_SetItem:PyTupleObject*:p:0:
-PyTuple_SetItem:int:pos::
-PyTuple_SetItem:PyObject*:o:0:
-
-PyTuple_Size:int:::
-PyTuple_Size:PyTupleObject*:p:0:
-
-PyType_GenericAlloc:PyObject*::+1:
-PyType_GenericAlloc:PyObject*:type:0:
-PyType_GenericAlloc:int:nitems:0:
-
-PyType_GenericNew:PyObject*::+1:
-PyType_GenericNew:PyObject*:type:0:
-PyType_GenericNew:PyObject*:args:0:
-PyType_GenericNew:PyObject*:kwds:0:
-
-PyUnicode_Check:int:::
-PyUnicode_Check:PyObject*:o:0:
-
-PyUnicode_GET_SIZE:int:::
-PyUnicode_GET_SIZE:PyObject*:o:0:
-
-PyUnicode_GET_DATA_SIZE:int:::
-PyUnicode_GET_DATA_SIZE:PyObject*:o:0:
-
-PyUnicode_AS_UNICODE:Py_UNICODE*:::
-PyUnicode_AS_UNICODE:PyObject*:o:0:
-
-PyUnicode_AS_DATA:const char*:::
-PyUnicode_AS_DATA:PyObject*:o:0:
-
-Py_UNICODE_ISSPACE:int:::
-Py_UNICODE_ISSPACE:Py_UNICODE:ch::
-
-Py_UNICODE_ISLOWER:int:::
-Py_UNICODE_ISLOWER:Py_UNICODE:ch::
-
-Py_UNICODE_ISUPPER:int:::
-Py_UNICODE_ISUPPER:Py_UNICODE:ch::
-
-Py_UNICODE_ISTITLE:int:::
-Py_UNICODE_ISTITLE:Py_UNICODE:ch::
-
-Py_UNICODE_ISLINEBREAK:int:::
-Py_UNICODE_ISLINEBREAK:Py_UNICODE:ch::
-
-Py_UNICODE_ISDECIMAL:int:::
-Py_UNICODE_ISDECIMAL:Py_UNICODE:ch::
-
-Py_UNICODE_ISDIGIT:int:::
-Py_UNICODE_ISDIGIT:Py_UNICODE:ch::
-
-Py_UNICODE_ISNUMERIC:int:::
-Py_UNICODE_ISNUMERIC:Py_UNICODE:ch::
-
-Py_UNICODE_TOLOWER:Py_UNICODE:::
-Py_UNICODE_TOLOWER:Py_UNICODE:ch::
-
-Py_UNICODE_TOUPPER:Py_UNICODE:::
-Py_UNICODE_TOUPPER:Py_UNICODE:ch::
-
-Py_UNICODE_TOTITLE:Py_UNICODE:::
-Py_UNICODE_TOTITLE:Py_UNICODE:ch::
-
-Py_UNICODE_TODECIMAL:int:::
-Py_UNICODE_TODECIMAL:Py_UNICODE:ch::
-
-Py_UNICODE_TODIGIT:int:::
-Py_UNICODE_TODIGIT:Py_UNICODE:ch::
-
-Py_UNICODE_TONUMERIC:double:::
-Py_UNICODE_TONUMERIC:Py_UNICODE:ch::
-
-PyUnicode_FromUnicode:PyObject*::+1:
-PyUnicode_FromUnicode:const Py_UNICODE*:u::
-PyUnicode_FromUnicode:int:size::
-
-PyUnicode_AsUnicode:Py_UNICODE*:::
-PyUnicode_AsUnicode:PyObject :*unicode:0:
-
-PyUnicode_GetSize:int:::
-PyUnicode_GetSize:PyObject :*unicode:0:
-
-PyUnicode_FromObject:PyObject*::+1:
-PyUnicode_FromObject:PyObject*:*obj:0:
-
-PyUnicode_FromEncodedObject:PyObject*::+1:
-PyUnicode_FromEncodedObject:PyObject*:*obj:0:
-PyUnicode_FromEncodedObject:const char*:encoding::
-PyUnicode_FromEncodedObject:const char*:errors::
-
-PyUnicode_FromWideChar:PyObject*::+1:
-PyUnicode_FromWideChar:const wchar_t*:w::
-PyUnicode_FromWideChar:int:size::
-
-PyUnicode_AsWideChar:int:::
-PyUnicode_AsWideChar:PyObject*:*unicode:0:
-PyUnicode_AsWideChar:wchar_t*:w::
-PyUnicode_AsWideChar:int:size::
-
-PyUnicode_Decode:PyObject*::+1:
-PyUnicode_Decode:const char*:s::
-PyUnicode_Decode:int:size::
-PyUnicode_Decode:const char*:encoding::
-PyUnicode_Decode:const char*:errors::
-
-PyUnicode_Encode:PyObject*::+1:
-PyUnicode_Encode:const Py_UNICODE*:s::
-PyUnicode_Encode:int:size::
-PyUnicode_Encode:const char*:encoding::
-PyUnicode_Encode:const char*:errors::
-
-PyUnicode_AsEncodedString:PyObject*::+1:
-PyUnicode_AsEncodedString:PyObject*:unicode::
-PyUnicode_AsEncodedString:const char*:encoding::
-PyUnicode_AsEncodedString:const char*:errors::
-
-PyUnicode_DecodeUTF8:PyObject*::+1:
-PyUnicode_DecodeUTF8:const char*:s::
-PyUnicode_DecodeUTF8:int:size::
-PyUnicode_DecodeUTF8:const char*:errors::
-
-PyUnicode_EncodeUTF8:PyObject*::+1:
-PyUnicode_EncodeUTF8:const Py_UNICODE*:s::
-PyUnicode_EncodeUTF8:int:size::
-PyUnicode_EncodeUTF8:const char*:errors::
-
-PyUnicode_AsUTF8String:PyObject*::+1:
-PyUnicode_AsUTF8String:PyObject*:unicode::
-
-PyUnicode_DecodeUTF16:PyObject*::+1:
-PyUnicode_DecodeUTF16:const char*:s::
-PyUnicode_DecodeUTF16:int:size::
-PyUnicode_DecodeUTF16:const char*:errors::
-PyUnicode_DecodeUTF16:int*:byteorder::
-
-PyUnicode_EncodeUTF16:PyObject*::+1:
-PyUnicode_EncodeUTF16:const Py_UNICODE*:s::
-PyUnicode_EncodeUTF16:int:size::
-PyUnicode_EncodeUTF16:const char*:errors::
-PyUnicode_EncodeUTF16:int:byteorder::
-
-PyUnicode_AsUTF16String:PyObject*::+1:
-PyUnicode_AsUTF16String:PyObject*:unicode::
-
-PyUnicode_DecodeUnicodeEscape:PyObject*::+1:
-PyUnicode_DecodeUnicodeEscape:const char*:s::
-PyUnicode_DecodeUnicodeEscape:int:size::
-PyUnicode_DecodeUnicodeEscape:const char*:errors::
-
-PyUnicode_EncodeUnicodeEscape:PyObject*::+1:
-PyUnicode_EncodeUnicodeEscape:const Py_UNICODE*:s::
-PyUnicode_EncodeUnicodeEscape:int:size::
-PyUnicode_EncodeUnicodeEscape:const char*:errors::
-
-PyUnicode_AsUnicodeEscapeString:PyObject*::+1:
-PyUnicode_AsUnicodeEscapeString:PyObject*:unicode::
-
-PyUnicode_DecodeRawUnicodeEscape:PyObject*::+1:
-PyUnicode_DecodeRawUnicodeEscape:const char*:s::
-PyUnicode_DecodeRawUnicodeEscape:int:size::
-PyUnicode_DecodeRawUnicodeEscape:const char*:errors::
-
-PyUnicode_EncodeRawUnicodeEscape:PyObject*::+1:
-PyUnicode_EncodeRawUnicodeEscape:const Py_UNICODE*:s::
-PyUnicode_EncodeRawUnicodeEscape:int:size::
-PyUnicode_EncodeRawUnicodeEscape:const char*:errors::
-
-PyUnicode_AsRawUnicodeEscapeString:PyObject*::+1:
-PyUnicode_AsRawUnicodeEscapeString:PyObject*:unicode::
-
-PyUnicode_DecodeLatin1:PyObject*::+1:
-PyUnicode_DecodeLatin1:const char*:s::
-PyUnicode_DecodeLatin1:int:size::
-PyUnicode_DecodeLatin1:const char*:errors::
-
-PyUnicode_EncodeLatin1:PyObject*::+1:
-PyUnicode_EncodeLatin1:const Py_UNICODE*:s::
-PyUnicode_EncodeLatin1:int:size::
-PyUnicode_EncodeLatin1:const char*:errors::
-
-PyUnicode_AsLatin1String:PyObject*::+1:
-PyUnicode_AsLatin1String:PyObject*:unicode::
-
-PyUnicode_DecodeASCII:PyObject*::+1:
-PyUnicode_DecodeASCII:const char*:s::
-PyUnicode_DecodeASCII:int:size::
-PyUnicode_DecodeASCII:const char*:errors::
-
-PyUnicode_EncodeASCII:PyObject*::+1:
-PyUnicode_EncodeASCII:const Py_UNICODE*:s::
-PyUnicode_EncodeASCII:int:size::
-PyUnicode_EncodeASCII:const char*:errors::
-
-PyUnicode_AsASCIIString:PyObject*::+1:
-PyUnicode_AsASCIIString:PyObject*:unicode::
-
-PyUnicode_DecodeCharmap:PyObject*::+1:
-PyUnicode_DecodeCharmap:const char*:s::
-PyUnicode_DecodeCharmap:int:size::
-PyUnicode_DecodeCharmap:PyObject*:mapping:0:
-PyUnicode_DecodeCharmap:const char*:errors::
-
-PyUnicode_EncodeCharmap:PyObject*::+1:
-PyUnicode_EncodeCharmap:const Py_UNICODE*:s::
-PyUnicode_EncodeCharmap:int:size::
-PyUnicode_EncodeCharmap:PyObject*:mapping:0:
-PyUnicode_EncodeCharmap:const char*:errors::
-
-PyUnicode_AsCharmapString:PyObject*::+1:
-PyUnicode_AsCharmapString:PyObject*:unicode:0:
-PyUnicode_AsCharmapString:PyObject*:mapping:0:
-
-PyUnicode_TranslateCharmap:PyObject*::+1:
-PyUnicode_TranslateCharmap:const Py_UNICODE*:s::
-PyUnicode_TranslateCharmap:int:size::
-PyUnicode_TranslateCharmap:PyObject*:table:0:
-PyUnicode_TranslateCharmap:const char*:errors::
-
-PyUnicode_DecodeMBCS:PyObject*::+1:
-PyUnicode_DecodeMBCS:const char*:s::
-PyUnicode_DecodeMBCS:int:size::
-PyUnicode_DecodeMBCS:const char*:errors::
-
-PyUnicode_EncodeMBCS:PyObject*::+1:
-PyUnicode_EncodeMBCS:const Py_UNICODE*:s::
-PyUnicode_EncodeMBCS:int:size::
-PyUnicode_EncodeMBCS:const char*:errors::
-
-PyUnicode_AsMBCSString:PyObject*::+1:
-PyUnicode_AsMBCSString:PyObject*:unicode::
-
-PyUnicode_Concat:PyObject*::+1:
-PyUnicode_Concat:PyObject*:left:0:
-PyUnicode_Concat:PyObject*:right:0:
-
-PyUnicode_Split:PyObject*::+1:
-PyUnicode_Split:PyObject*:left:0:
-PyUnicode_Split:PyObject*:right:0:
-PyUnicode_Split:int:maxsplit::
-
-PyUnicode_Splitlines:PyObject*::+1:
-PyUnicode_Splitlines:PyObject*:s:0:
-PyUnicode_Splitlines:int:maxsplit::
-
-PyUnicode_Translate:PyObject*::+1:
-PyUnicode_Translate:PyObject*:str:0:
-PyUnicode_Translate:PyObject*:table:0:
-PyUnicode_Translate:const char*:errors::
-
-PyUnicode_Join:PyObject*::+1:
-PyUnicode_Join:PyObject*:separator:0:
-PyUnicode_Join:PyObject*:seq:0:
-
-PyUnicode_Tailmatch:PyObject*::+1:
-PyUnicode_Tailmatch:PyObject*:str:0:
-PyUnicode_Tailmatch:PyObject*:substr:0:
-PyUnicode_Tailmatch:int:start::
-PyUnicode_Tailmatch:int:end::
-PyUnicode_Tailmatch:int:direction::
-
-PyUnicode_Find:int:::
-PyUnicode_Find:PyObject*:str:0:
-PyUnicode_Find:PyObject*:substr:0:
-PyUnicode_Find:int:start::
-PyUnicode_Find:int:end::
-PyUnicode_Find:int:direction::
-
-PyUnicode_Count:int:::
-PyUnicode_Count:PyObject*:str:0:
-PyUnicode_Count:PyObject*:substr:0:
-PyUnicode_Count:int:start::
-PyUnicode_Count:int:end::
-
-PyUnicode_Replace:PyObject*::+1:
-PyUnicode_Replace:PyObject*:str:0:
-PyUnicode_Replace:PyObject*:substr:0:
-PyUnicode_Replace:PyObject*:replstr:0:
-PyUnicode_Replace:int:maxcount::
-
-PyUnicode_Compare:int:::
-PyUnicode_Compare:PyObject*:left:0:
-PyUnicode_Compare:PyObject*:right:0:
-
-PyUnicode_Format:PyObject*::+1:
-PyUnicode_Format:PyObject*:format:0:
-PyUnicode_Format:PyObject*:args:0:
-
-PyUnicode_Contains:int:::
-PyUnicode_Contains:PyObject*:container:0:
-PyUnicode_Contains:PyObject*:element:0:
-
-PyWeakref_GET_OBJECT:PyObject*::0:
-PyWeakref_GET_OBJECT:PyObject*:ref:0:
-
-PyWeakref_GetObject:PyObject*::0:
-PyWeakref_GetObject:PyObject*:ref:0:
-
-PyWeakref_NewProxy:PyObject*::+1:
-PyWeakref_NewProxy:PyObject*:ob:0:
-PyWeakref_NewProxy:PyObject*:callback:0:
-
-PyWeakref_NewRef:PyObject*::+1:
-PyWeakref_NewRef:PyObject*:ob:0:
-PyWeakref_NewRef:PyObject*:callback:0:
-
-PyWrapper_New:PyObject*::+1:
-PyWrapper_New:PyObject*:d:0:
-PyWrapper_New:PyObject*:self:0:
-
-Py_AtExit:int:::
-Py_AtExit:void (*)():func::
-
-Py_BuildValue:PyObject*::+1:
-Py_BuildValue:char*:format::
-
-Py_CompileString:PyObject*::+1:
-Py_CompileString:char*:str::
-Py_CompileString:char*:filename::
-Py_CompileString:int:start::
-
-Py_DECREF:void:::
-Py_DECREF:PyObject*:o:-1:
-
-Py_EndInterpreter:void:::
-Py_EndInterpreter:PyThreadState*:tstate::
-
-Py_Exit:void:::
-Py_Exit:int:status::
-
-Py_FatalError:void:::
-Py_FatalError:char*:message::
-
-Py_FdIsInteractive:int:::
-Py_FdIsInteractive:FILE*:fp::
-Py_FdIsInteractive:char*:filename::
-
-Py_Finalize:void:::
-
-Py_FindMethod:PyObject*::+1:
-Py_FindMethod:PyMethodDef[]:methods::
-Py_FindMethod:PyObject*:self:+1:
-Py_FindMethod:char*:name::
-
-Py_GetBuildInfoconst:char*:::
-
-Py_GetCompilerconst:char*:::
-
-Py_GetCopyrightconst:char*:::
-
-Py_GetExecPrefix:char*:::
-
-Py_GetPath:char*:::
-
-Py_GetPlatformconst:char*:::
-
-Py_GetPrefix:char*:::
-
-Py_GetProgramFullPath:char*:::
-
-Py_GetProgramName:char*:::
-
-Py_GetVersionconst:char*:::
-
-Py_INCREF:void:::
-Py_INCREF:PyObject*:o:+1:
-
-Py_Initialize:void:::
-
-Py_IsInitialized:int:::
-
-Py_NewInterpreter:PyThreadState*:::
-
-Py_SetProgramName:void:::
-Py_SetProgramName:char*:name::
-
-Py_XDECREF:void:::
-Py_XDECREF:PyObject*:o:-1:if o is not NULL
-
-Py_XINCREF:void:::
-Py_XINCREF:PyObject*:o:+1:if o is not NULL
-
-_PyImport_FindExtension:PyObject*::0:??? see PyImport_AddModule
-_PyImport_FindExtension:char*:::
-_PyImport_FindExtension:char*:::
-
-_PyImport_Fini:void:::
-
-_PyImport_FixupExtension:PyObject*:::???
-_PyImport_FixupExtension:char*:::
-_PyImport_FixupExtension:char*:::
-
-_PyImport_Init:void:::
-
-_PyObject_Del:void:::
-_PyObject_Del:PyObject*:op:0:
-
-_PyObject_New:PyObject*::+1:
-_PyObject_New:PyTypeObject*:type:0:
-
-_PyObject_NewVar:PyObject*::+1:
-_PyObject_NewVar:PyTypeObject*:type:0:
-_PyObject_NewVar:int:size::
-
-_PyString_Resize:int:::
-_PyString_Resize:PyObject**:string:+1:
-_PyString_Resize:int:newsize::
-
-_PyTuple_Resize:int:::
-_PyTuple_Resize:PyTupleObject**:p:+1:
-_PyTuple_Resize:int:new::
-
-_Py_c_diff:Py_complex:::
-_Py_c_diff:Py_complex:left::
-_Py_c_diff:Py_complex:right::
-
-_Py_c_neg:Py_complex:::
-_Py_c_neg:Py_complex:complex::
-
-_Py_c_pow:Py_complex:::
-_Py_c_pow:Py_complex:num::
-_Py_c_pow:Py_complex:exp::
-
-_Py_c_prod:Py_complex:::
-_Py_c_prod:Py_complex:left::
-_Py_c_prod:Py_complex:right::
-
-_Py_c_quot:Py_complex:::
-_Py_c_quot:Py_complex:dividend::
-_Py_c_quot:Py_complex:divisor::
-
-_Py_c_sum:Py_complex:::
-_Py_c_sum:Py_complex:left::
-_Py_c_sum:Py_complex:right::
diff --git a/Doc/api/utilities.tex b/Doc/api/utilities.tex
deleted file mode 100644
index a17f705052..0000000000
--- a/Doc/api/utilities.tex
+++ /dev/null
@@ -1,862 +0,0 @@
-\chapter{Utilities \label{utilities}}
-
-The functions in this chapter perform various utility tasks, ranging
-from helping C code be more portable across platforms, using Python
-modules from C, and parsing function arguments and constructing Python
-values from C values.
-
-
-\section{Operating System Utilities \label{os}}
-
-\begin{cfuncdesc}{int}{Py_FdIsInteractive}{FILE *fp, char *filename}
- Return true (nonzero) if the standard I/O file \var{fp} with name
- \var{filename} is deemed interactive. This is the case for files
- for which \samp{isatty(fileno(\var{fp}))} is true. If the global
- flag \cdata{Py_InteractiveFlag} is true, this function also returns
- true if the \var{filename} pointer is \NULL{} or if the name is
- equal to one of the strings \code{''} or \code{'???'}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{long}{PyOS_GetLastModificationTime}{char *filename}
- Return the time of last modification of the file \var{filename}.
- The result is encoded in the same way as the timestamp returned by
- the standard C library function \cfunction{time()}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyOS_AfterFork}{}
- Function to update some internal state after a process fork; this
- should be called in the new process if the Python interpreter will
- continue to be used. If a new executable is loaded into the new
- process, this function does not need to be called.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyOS_CheckStack}{}
- Return true when the interpreter runs out of stack space. This is a
- reliable check, but is only available when \constant{USE_STACKCHECK}
- is defined (currently on Windows using the Microsoft Visual \Cpp{}
- compiler and on the Macintosh). \constant{USE_CHECKSTACK} will be
- defined automatically; you should never change the definition in
- your own code.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_getsig}{int i}
- Return the current signal handler for signal \var{i}. This is a
- thin wrapper around either \cfunction{sigaction()} or
- \cfunction{signal()}. Do not call those functions directly!
- \ctype{PyOS_sighandler_t} is a typedef alias for \ctype{void
- (*)(int)}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyOS_sighandler_t}{PyOS_setsig}{int i, PyOS_sighandler_t h}
- Set the signal handler for signal \var{i} to be \var{h}; return the
- old signal handler. This is a thin wrapper around either
- \cfunction{sigaction()} or \cfunction{signal()}. Do not call those
- functions directly! \ctype{PyOS_sighandler_t} is a typedef alias
- for \ctype{void (*)(int)}.
-\end{cfuncdesc}
-
-
-\section{Process Control \label{processControl}}
-
-\begin{cfuncdesc}{void}{Py_FatalError}{const char *message}
- Print a fatal error message and kill the process. No cleanup is
- performed. This function should only be invoked when a condition is
- detected that would make it dangerous to continue using the Python
- interpreter; e.g., when the object administration appears to be
- corrupted. On \UNIX, the standard C library function
- \cfunction{abort()}\ttindex{abort()} is called which will attempt to
- produce a \file{core} file.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{Py_Exit}{int status}
- Exit the current process. This calls
- \cfunction{Py_Finalize()}\ttindex{Py_Finalize()} and then calls the
- standard C library function
- \code{exit(\var{status})}\ttindex{exit()}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{Py_AtExit}{void (*func) ()}
- Register a cleanup function to be called by
- \cfunction{Py_Finalize()}\ttindex{Py_Finalize()}. The cleanup
- function will be called with no arguments and should return no
- value. At most 32 \index{cleanup functions}cleanup functions can be
- registered. When the registration is successful,
- \cfunction{Py_AtExit()} returns \code{0}; on failure, it returns
- \code{-1}. The cleanup function registered last is called first.
- Each cleanup function will be called at most once. Since Python's
- internal finallization will have completed before the cleanup
- function, no Python APIs should be called by \var{func}.
-\end{cfuncdesc}
-
-
-\section{Importing Modules \label{importing}}
-
-\begin{cfuncdesc}{PyObject*}{PyImport_ImportModule}{char *name}
- This is a simplified interface to
- \cfunction{PyImport_ImportModuleEx()} below, leaving the
- \var{globals} and \var{locals} arguments set to \NULL. When the
- \var{name} argument contains a dot (when it specifies a submodule of
- a package), the \var{fromlist} argument is set to the list
- \code{['*']} so that the return value is the named module rather
- than the top-level package containing it as would otherwise be the
- case. (Unfortunately, this has an additional side effect when
- \var{name} in fact specifies a subpackage instead of a submodule:
- the submodules specified in the package's \code{__all__} variable
- are \index{package variable!\code{__all__}}
- \withsubitem{(package variable)}{\ttindex{__all__}}loaded.) Return
- a new reference to the imported module, or \NULL{} with an exception
- set on failure (the module may still be created in this case ---
- examine \code{sys.modules} to find out).
- \withsubitem{(in module sys)}{\ttindex{modules}}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyImport_ImportModuleEx}{char *name,
- PyObject *globals, PyObject *locals, PyObject *fromlist}
- Import a module. This is best described by referring to the
- built-in Python function
- \function{__import__()}\bifuncindex{__import__}, as the standard
- \function{__import__()} function calls this function directly.
-
- The return value is a new reference to the imported module or
- top-level package, or \NULL{} with an exception set on failure (the
- module may still be created in this case). Like for
- \function{__import__()}, the return value when a submodule of a
- package was requested is normally the top-level package, unless a
- non-empty \var{fromlist} was given.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyImport_Import}{PyObject *name}
- This is a higher-level interface that calls the current ``import
- hook function''. It invokes the \function{__import__()} function
- from the \code{__builtins__} of the current globals. This means
- that the import is done using whatever import hooks are installed in
- the current environment, e.g. by \module{rexec}\refstmodindex{rexec}
- or \module{ihooks}\refstmodindex{ihooks}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyImport_ReloadModule}{PyObject *m}
- Reload a module. This is best described by referring to the
- built-in Python function \function{reload()}\bifuncindex{reload}, as
- the standard \function{reload()} function calls this function
- directly. Return a new reference to the reloaded module, or \NULL{}
- with an exception set on failure (the module still exists in this
- case).
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyImport_AddModule}{char *name}
- Return the module object corresponding to a module name. The
- \var{name} argument may be of the form \code{package.module}).
- First check the modules dictionary if there's one there, and if not,
- create a new one and insert in in the modules dictionary.
- Return \NULL{} with an exception set on failure.
- \note{This function does not load or import the module; if the
- module wasn't already loaded, you will get an empty module object.
- Use \cfunction{PyImport_ImportModule()} or one of its variants to
- import a module. Package structures implied by a dotted name for
- \var{name} are not created if not already present.}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyImport_ExecCodeModule}{char *name, PyObject *co}
- Given a module name (possibly of the form \code{package.module}) and
- a code object read from a Python bytecode file or obtained from the
- built-in function \function{compile()}\bifuncindex{compile}, load
- the module. Return a new reference to the module object, or \NULL{}
- with an exception set if an error occurred (the module may still be
- created in this case). This function would reload the module if it
- was already imported. If \var{name} points to a dotted name of the
- form \code{package.module}, any package structures not already
- created will still not be created.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{long}{PyImport_GetMagicNumber}{}
- Return the magic number for Python bytecode files
- (a.k.a. \file{.pyc} and \file{.pyo} files). The magic number should
- be present in the first four bytes of the bytecode file, in
- little-endian byte order.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyImport_GetModuleDict}{}
- Return the dictionary used for the module administration
- (a.k.a.\ \code{sys.modules}). Note that this is a per-interpreter
- variable.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{_PyImport_Init}{}
- Initialize the import mechanism. For internal use only.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyImport_Cleanup}{}
- Empty the module table. For internal use only.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{_PyImport_Fini}{}
- Finalize the import mechanism. For internal use only.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{_PyImport_FindExtension}{char *, char *}
- For internal use only.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{_PyImport_FixupExtension}{char *, char *}
- For internal use only.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyImport_ImportFrozenModule}{char *name}
- Load a frozen module named \var{name}. Return \code{1} for success,
- \code{0} if the module is not found, and \code{-1} with an exception
- set if the initialization failed. To access the imported module on
- a successful load, use \cfunction{PyImport_ImportModule()}. (Note
- the misnomer --- this function would reload the module if it was
- already imported.)
-\end{cfuncdesc}
-
-\begin{ctypedesc}[_frozen]{struct _frozen}
- This is the structure type definition for frozen module descriptors,
- as generated by the \program{freeze}\index{freeze utility} utility
- (see \file{Tools/freeze/} in the Python source distribution). Its
- definition, found in \file{Include/import.h}, is:
-
-\begin{verbatim}
-struct _frozen {
- char *name;
- unsigned char *code;
- int size;
-};
-\end{verbatim}
-\end{ctypedesc}
-
-\begin{cvardesc}{struct _frozen*}{PyImport_FrozenModules}
- This pointer is initialized to point to an array of \ctype{struct
- _frozen} records, terminated by one whose members are all \NULL{} or
- zero. When a frozen module is imported, it is searched in this
- table. Third-party code could play tricks with this to provide a
- dynamically created collection of frozen modules.
-\end{cvardesc}
-
-\begin{cfuncdesc}{int}{PyImport_AppendInittab}{char *name,
- void (*initfunc)(void)}
- Add a single module to the existing table of built-in modules. This
- is a convenience wrapper around
- \cfunction{PyImport_ExtendInittab()}, returning \code{-1} if the
- table could not be extended. The new module can be imported by the
- name \var{name}, and uses the function \var{initfunc} as the
- initialization function called on the first attempted import. This
- should be called before \cfunction{Py_Initialize()}.
-\end{cfuncdesc}
-
-\begin{ctypedesc}[_inittab]{struct _inittab}
- Structure describing a single entry in the list of built-in
- modules. Each of these structures gives the name and initialization
- function for a module built into the interpreter. Programs which
- embed Python may use an array of these structures in conjunction
- with \cfunction{PyImport_ExtendInittab()} to provide additional
- built-in modules. The structure is defined in
- \file{Include/import.h} as:
-
-\begin{verbatim}
-struct _inittab {
- char *name;
- void (*initfunc)(void);
-};
-\end{verbatim}
-\end{ctypedesc}
-
-\begin{cfuncdesc}{int}{PyImport_ExtendInittab}{struct _inittab *newtab}
- Add a collection of modules to the table of built-in modules. The
- \var{newtab} array must end with a sentinel entry which contains
- \NULL{} for the \member{name} field; failure to provide the sentinel
- value can result in a memory fault. Returns \code{0} on success or
- \code{-1} if insufficient memory could be allocated to extend the
- internal table. In the event of failure, no modules are added to
- the internal table. This should be called before
- \cfunction{Py_Initialize()}.
-\end{cfuncdesc}
-
-
-\section{Data marshalling support \label{marshalling-utils}}
-
-These routines allow C code to work with serialized objects using the
-same data format as the \module{marshal} module. There are functions
-to write data into the serialization format, and additional functions
-that can be used to read the data back. Files used to store marshalled
-data must be opened in binary mode.
-
-Numeric values are stored with the least significant byte first.
-
-\begin{cfuncdesc}{void}{PyMarshal_WriteLongToFile}{long value, FILE *file}
- Marshal a \ctype{long} integer, \var{value}, to \var{file}. This
- will only write the least-significant 32 bits of \var{value};
- regardless of the size of the native \ctype{long} type.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{void}{PyMarshal_WriteObjectToFile}{PyObject *value,
- FILE *file}
- Marshal a Python object, \var{value}, to \var{file}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyMarshal_WriteObjectToString}{PyObject *value}
- Return a string object containing the marshalled representation of
- \var{value}.
-\end{cfuncdesc}
-
-The following functions allow marshalled values to be read back in.
-
-XXX What about error detection? It appears that reading past the end
-of the file will always result in a negative numeric value (where
-that's relevant), but it's not clear that negative values won't be
-handled properly when there's no error. What's the right way to tell?
-Should only non-negative values be written using these routines?
-
-\begin{cfuncdesc}{long}{PyMarshal_ReadLongFromFile}{FILE *file}
- Return a C \ctype{long} from the data stream in a \ctype{FILE*}
- opened for reading. Only a 32-bit value can be read in using
- this function, regardless of the native size of \ctype{long}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyMarshal_ReadShortFromFile}{FILE *file}
- Return a C \ctype{short} from the data stream in a \ctype{FILE*}
- opened for reading. Only a 16-bit value can be read in using
- this function, regardless of the native size of \ctype{short}.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyMarshal_ReadObjectFromFile}{FILE *file}
- Return a Python object from the data stream in a \ctype{FILE*}
- opened for reading. On error, sets the appropriate exception
- (\exception{EOFError} or \exception{TypeError}) and returns \NULL.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyMarshal_ReadLastObjectFromFile}{FILE *file}
- Return a Python object from the data stream in a \ctype{FILE*}
- opened for reading. Unlike
- \cfunction{PyMarshal_ReadObjectFromFile()}, this function assumes
- that no further objects will be read from the file, allowing it to
- aggressively load file data into memory so that the de-serialization
- can operate from data in memory rather than reading a byte at a time
- from the file. Only use these variant if you are certain that you
- won't be reading anything else from the file. On error, sets the
- appropriate exception (\exception{EOFError} or
- \exception{TypeError}) and returns \NULL.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyMarshal_ReadObjectFromString}{char *string,
- int len}
- Return a Python object from the data stream in a character buffer
- containing \var{len} bytes pointed to by \var{string}. On error,
- sets the appropriate exception (\exception{EOFError} or
- \exception{TypeError}) and returns \NULL.
-\end{cfuncdesc}
-
-
-\section{Parsing arguments and building values
- \label{arg-parsing}}
-
-These functions are useful when creating your own extensions functions
-and methods. Additional information and examples are available in
-\citetitle[../ext/ext.html]{Extending and Embedding the Python
-Interpreter}.
-
-The first three of these functions described,
-\cfunction{PyArg_ParseTuple()},
-\cfunction{PyArg_ParseTupleAndKeywords()}, and
-\cfunction{PyArg_Parse()}, all use \emph{format strings} which are
-used to tell the function about the expected arguments. The format
-strings use the same syntax for each of these functions.
-
-A format string consists of zero or more ``format units.'' A format
-unit describes one Python object; it is usually a single character or
-a parenthesized sequence of format units. With a few exceptions, a
-format unit that is not a parenthesized sequence normally corresponds
-to a single address argument to these functions. In the following
-description, the quoted form is the format unit; the entry in (round)
-parentheses is the Python object type that matches the format unit;
-and the entry in [square] brackets is the type of the C variable(s)
-whose address should be passed.
-
-\begin{description}
- \item[\samp{s} (string or Unicode object) {[char *]}]
- Convert a Python string or Unicode object to a C pointer to a
- character string. You must not provide storage for the string
- itself; a pointer to an existing string is stored into the character
- pointer variable whose address you pass. The C string is
- NUL-terminated. The Python string must not contain embedded NUL
- bytes; if it does, a \exception{TypeError} exception is raised.
- Unicode objects are converted to C strings using the default
- encoding. If this conversion fails, a \exception{UnicodeError} is
- raised.
-
- \item[\samp{s\#} (string, Unicode or any read buffer compatible object)
- {[char *, int]}]
- This variant on \samp{s} stores into two C variables, the first one
- a pointer to a character string, the second one its length. In this
- case the Python string may contain embedded null bytes. Unicode
- objects pass back a pointer to the default encoded string version of
- the object if such a conversion is possible. All other read-buffer
- compatible objects pass back a reference to the raw internal data
- representation.
-
- \item[\samp{z} (string or \code{None}) {[char *]}]
- Like \samp{s}, but the Python object may also be \code{None}, in
- which case the C pointer is set to \NULL.
-
- \item[\samp{z\#} (string or \code{None} or any read buffer
- compatible object) {[char *, int]}]
- This is to \samp{s\#} as \samp{z} is to \samp{s}.
-
- \item[\samp{u} (Unicode object) {[Py_UNICODE *]}]
- Convert a Python Unicode object to a C pointer to a NUL-terminated
- buffer of 16-bit Unicode (UTF-16) data. As with \samp{s}, there is
- no need to provide storage for the Unicode data buffer; a pointer to
- the existing Unicode data is stored into the \ctype{Py_UNICODE}
- pointer variable whose address you pass.
-
- \item[\samp{u\#} (Unicode object) {[Py_UNICODE *, int]}]
- This variant on \samp{u} stores into two C variables, the first one
- a pointer to a Unicode data buffer, the second one its length.
- Non-Unicode objects are handled by interpreting their read-buffer
- pointer as pointer to a \ctype{Py_UNICODE} array.
-
- \item[\samp{es} (string, Unicode object or character buffer
- compatible object) {[const char *encoding, char **buffer]}]
- This variant on \samp{s} is used for encoding Unicode and objects
- convertible to Unicode into a character buffer. It only works for
- encoded data without embedded NUL bytes.
-
- This format requires two arguments. The first is only used as
- input, and must be a \ctype{char*} which points to the name of an
- encoding as a NUL-terminated string, or \NULL, in which case the
- default encoding is used. An exception is raised if the named
- encoding is not known to Python. The second argument must be a
- \ctype{char**}; the value of the pointer it references will be set
- to a buffer with the contents of the argument text. The text will
- be encoded in the encoding specified by the first argument.
-
- \cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
- size, copy the encoded data into this buffer and adjust
- \var{*buffer} to reference the newly allocated storage. The caller
- is responsible for calling \cfunction{PyMem_Free()} to free the
- allocated buffer after use.
-
- \item[\samp{et} (string, Unicode object or character buffer
- compatible object) {[const char *encoding, char **buffer]}]
- Same as \samp{es} except that 8-bit string objects are passed
- through without recoding them. Instead, the implementation assumes
- that the string object uses the encoding passed in as parameter.
-
- \item[\samp{es\#} (string, Unicode object or character buffer compatible
- object) {[const char *encoding, char **buffer, int *buffer_length]}]
- This variant on \samp{s\#} is used for encoding Unicode and objects
- convertible to Unicode into a character buffer. Unlike the
- \samp{es} format, this variant allows input data which contains NUL
- characters.
-
- It requires three arguments. The first is only used as input, and
- must be a \ctype{char*} which points to the name of an encoding as a
- NUL-terminated string, or \NULL, in which case the default encoding
- is used. An exception is raised if the named encoding is not known
- to Python. The second argument must be a \ctype{char**}; the value
- of the pointer it references will be set to a buffer with the
- contents of the argument text. The text will be encoded in the
- encoding specified by the first argument. The third argument must
- be a pointer to an integer; the referenced integer will be set to
- the number of bytes in the output buffer.
-
- There are two modes of operation:
-
- If \var{*buffer} points a \NULL{} pointer, the function will
- allocate a buffer of the needed size, copy the encoded data into
- this buffer and set \var{*buffer} to reference the newly allocated
- storage. The caller is responsible for calling
- \cfunction{PyMem_Free()} to free the allocated buffer after usage.
-
- If \var{*buffer} points to a non-\NULL{} pointer (an already
- allocated buffer), \cfunction{PyArg_ParseTuple()} will use this
- location as the buffer and interpret the initial value of
- \var{*buffer_length} as the buffer size. It will then copy the
- encoded data into the buffer and NUL-terminate it. If the buffer
- is not large enough, a \exception{ValueError} will be set.
-
- In both cases, \var{*buffer_length} is set to the length of the
- encoded data without the trailing NUL byte.
-
- \item[\samp{et\#} (string, Unicode object or character buffer compatible
- object) {[const char *encoding, char **buffer]}]
- Same as \samp{es\#} except that string objects are passed through
- without recoding them. Instead, the implementation assumes that the
- string object uses the encoding passed in as parameter.
-
- \item[\samp{b} (integer) {[char]}]
- Convert a Python integer to a tiny int, stored in a C \ctype{char}.
-
- \item[\samp{B} (integer) {[unsigned char]}]
- Convert a Python integer to a tiny int without overflow checking,
- stored in a C \ctype{unsigned char}. \versionadded{2.3}
-
- \item[\samp{h} (integer) {[short int]}]
- Convert a Python integer to a C \ctype{short int}.
-
- \item[\samp{H} (integer) {[unsigned short int]}]
- Convert a Python integer to a C \ctype{unsigned short int}, without
- overflow checking. \versionadded{2.3}
-
- \item[\samp{i} (integer) {[int]}]
- Convert a Python integer to a plain C \ctype{int}.
-
- \item[\samp{I} (integer) {[unsigned int]}]
- Convert a Python integer to a C \ctype{unsigned int}, without
- overflow checking. \versionadded{2.3}
-
- \item[\samp{l} (integer) {[long int]}]
- Convert a Python integer to a C \ctype{long int}.
-
- \item[\samp{k} (integer) {[unsigned long]}]
- Convert a Python integer to a C \ctype{unsigned long} without
- overflow checking. \versionadded{2.3}
-
- \item[\samp{L} (integer) {[PY_LONG_LONG]}]
- Convert a Python integer to a C \ctype{long long}. This format is
- only available on platforms that support \ctype{long long} (or
- \ctype{_int64} on Windows).
-
- \item[\samp{K} (integer) {[unsigned PY_LONG_LONG]}]
- Convert a Python integer to a C \ctype{unsigned long long}
- without overflow checking. This format is only available on
- platforms that support \ctype{unsigned long long} (or
- \ctype{unsigned _int64} on Windows). \versionadded{2.3}
-
- \item[\samp{c} (string of length 1) {[char]}]
- Convert a Python character, represented as a string of length 1, to
- a C \ctype{char}.
-
- \item[\samp{f} (float) {[float]}]
- Convert a Python floating point number to a C \ctype{float}.
-
- \item[\samp{d} (float) {[double]}]
- Convert a Python floating point number to a C \ctype{double}.
-
- \item[\samp{D} (complex) {[Py_complex]}]
- Convert a Python complex number to a C \ctype{Py_complex} structure.
-
- \item[\samp{O} (object) {[PyObject *]}]
- Store a Python object (without any conversion) in a C object
- pointer. The C program thus receives the actual object that was
- passed. The object's reference count is not increased. The pointer
- stored is not \NULL.
-
- \item[\samp{O!} (object) {[\var{typeobject}, PyObject *]}]
- Store a Python object in a C object pointer. This is similar to
- \samp{O}, but takes two C arguments: the first is the address of a
- Python type object, the second is the address of the C variable (of
- type \ctype{PyObject*}) into which the object pointer is stored. If
- the Python object does not have the required type,
- \exception{TypeError} is raised.
-
- \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
- Convert a Python object to a C variable through a \var{converter}
- function. This takes two arguments: the first is a function, the
- second is the address of a C variable (of arbitrary type), converted
- to \ctype{void *}. The \var{converter} function in turn is called
- as follows:
-
- \var{status}\code{ = }\var{converter}\code{(}\var{object},
- \var{address}\code{);}
-
- where \var{object} is the Python object to be converted and
- \var{address} is the \ctype{void*} argument that was passed to the
- \cfunction{PyArg_Parse*()} function. The returned \var{status}
- should be \code{1} for a successful conversion and \code{0} if the
- conversion has failed. When the conversion fails, the
- \var{converter} function should raise an exception.
-
- \item[\samp{S} (string) {[PyStringObject *]}]
- Like \samp{O} but requires that the Python object is a string
- object. Raises \exception{TypeError} if the object is not a string
- object. The C variable may also be declared as \ctype{PyObject*}.
-
- \item[\samp{U} (Unicode string) {[PyUnicodeObject *]}]
- Like \samp{O} but requires that the Python object is a Unicode
- object. Raises \exception{TypeError} if the object is not a Unicode
- object. The C variable may also be declared as \ctype{PyObject*}.
-
- \item[\samp{t\#} (read-only character buffer) {[char *, int]}]
- Like \samp{s\#}, but accepts any object which implements the
- read-only buffer interface. The \ctype{char*} variable is set to
- point to the first byte of the buffer, and the \ctype{int} is set to
- the length of the buffer. Only single-segment buffer objects are
- accepted; \exception{TypeError} is raised for all others.
-
- \item[\samp{w} (read-write character buffer) {[char *]}]
- Similar to \samp{s}, but accepts any object which implements the
- read-write buffer interface. The caller must determine the length
- of the buffer by other means, or use \samp{w\#} instead. Only
- single-segment buffer objects are accepted; \exception{TypeError} is
- raised for all others.
-
- \item[\samp{w\#} (read-write character buffer) {[char *, int]}]
- Like \samp{s\#}, but accepts any object which implements the
- read-write buffer interface. The \ctype{char *} variable is set to
- point to the first byte of the buffer, and the \ctype{int} is set to
- the length of the buffer. Only single-segment buffer objects are
- accepted; \exception{TypeError} is raised for all others.
-
- \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
- The object must be a Python sequence whose length is the number of
- format units in \var{items}. The C arguments must correspond to the
- individual format units in \var{items}. Format units for sequences
- may be nested.
-
- \note{Prior to Python version 1.5.2, this format specifier only
- accepted a tuple containing the individual parameters, not an
- arbitrary sequence. Code which previously caused
- \exception{TypeError} to be raised here may now proceed without an
- exception. This is not expected to be a problem for existing code.}
-\end{description}
-
-It is possible to pass Python long integers where integers are
-requested; however no proper range checking is done --- the most
-significant bits are silently truncated when the receiving field is
-too small to receive the value (actually, the semantics are inherited
-from downcasts in C --- your mileage may vary).
-
-A few other characters have a meaning in a format string. These may
-not occur inside nested parentheses. They are:
-
-\begin{description}
- \item[\samp{|}]
- Indicates that the remaining arguments in the Python argument list
- are optional. The C variables corresponding to optional arguments
- should be initialized to their default value --- when an optional
- argument is not specified, \cfunction{PyArg_ParseTuple()} does not
- touch the contents of the corresponding C variable(s).
-
- \item[\samp{:}]
- The list of format units ends here; the string after the colon is
- used as the function name in error messages (the ``associated
- value'' of the exception that \cfunction{PyArg_ParseTuple()}
- raises).
-
- \item[\samp{;}]
- The list of format units ends here; the string after the semicolon
- is used as the error message \emph{instead} of the default error
- message. Clearly, \samp{:} and \samp{;} mutually exclude each
- other.
-\end{description}
-
-Note that any Python object references which are provided to the
-caller are \emph{borrowed} references; do not decrement their
-reference count!
-
-Additional arguments passed to these functions must be addresses of
-variables whose type is determined by the format string; these are
-used to store values from the input tuple. There are a few cases, as
-described in the list of format units above, where these parameters
-are used as input values; they should match what is specified for the
-corresponding format unit in that case.
-
-For the conversion to succeed, the \var{arg} object must match the
-format and the format must be exhausted. On success, the
-\cfunction{PyArg_Parse*()} functions return true, otherwise they
-return false and raise an appropriate exception.
-
-\begin{cfuncdesc}{int}{PyArg_ParseTuple}{PyObject *args, char *format,
- \moreargs}
- Parse the parameters of a function that takes only positional
- parameters into local variables. Returns true on success; on
- failure, it returns false and raises the appropriate exception.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyArg_ParseTupleAndKeywords}{PyObject *args,
- PyObject *kw, char *format, char *keywords[],
- \moreargs}
- Parse the parameters of a function that takes both positional and
- keyword parameters into local variables. Returns true on success;
- on failure, it returns false and raises the appropriate exception.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyArg_Parse}{PyObject *args, char *format,
- \moreargs}
- Function used to deconstruct the argument lists of ``old-style''
- functions --- these are functions which use the
- \constant{METH_OLDARGS} parameter parsing method. This is not
- recommended for use in parameter parsing in new code, and most code
- in the standard interpreter has been modified to no longer use this
- for that purpose. It does remain a convenient way to decompose
- other tuples, however, and may continue to be used for that
- purpose.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyArg_UnpackTuple}{PyObject *args, char *name,
- int min, int max, \moreargs}
- A simpler form of parameter retrieval which does not use a format
- string to specify the types of the arguments. Functions which use
- this method to retrieve their parameters should be declared as
- \constant{METH_VARARGS} in function or method tables. The tuple
- containing the actual parameters should be passed as \var{args}; it
- must actually be a tuple. The length of the tuple must be at least
- \var{min} and no more than \var{max}; \var{min} and \var{max} may be
- equal. Additional arguments must be passed to the function, each of
- which should be a pointer to a \ctype{PyObject*} variable; these
- will be filled in with the values from \var{args}; they will contain
- borrowed references. The variables which correspond to optional
- parameters not given by \var{args} will not be filled in; these
- should be initialized by the caller.
- This function returns true on success and false if \var{args} is not
- a tuple or contains the wrong number of elements; an exception will
- be set if there was a failure.
-
- This is an example of the use of this function, taken from the
- sources for the \module{_weakref} helper module for weak references:
-
-\begin{verbatim}
-static PyObject *
-weakref_ref(PyObject *self, PyObject *args)
-{
- PyObject *object;
- PyObject *callback = NULL;
- PyObject *result = NULL;
-
- if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
- result = PyWeakref_NewRef(object, callback);
- }
- return result;
-}
-\end{verbatim}
-
- The call to \cfunction{PyArg_UnpackTuple()} in this example is
- entirely equivalent to this call to \cfunction{PyArg_ParseTuple()}:
-
-\begin{verbatim}
-PyArg_ParseTuple(args, "O|O:ref", &object, &callback)
-\end{verbatim}
-
- \versionadded{2.2}
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{Py_BuildValue}{char *format,
- \moreargs}
- Create a new value based on a format string similar to those
- accepted by the \cfunction{PyArg_Parse*()} family of functions and a
- sequence of values. Returns the value or \NULL{} in the case of an
- error; an exception will be raised if \NULL{} is returned.
-
- \cfunction{Py_BuildValue()} does not always build a tuple. It
- builds a tuple only if its format string contains two or more format
- units. If the format string is empty, it returns \code{None}; if it
- contains exactly one format unit, it returns whatever object is
- described by that format unit. To force it to return a tuple of
- size 0 or one, parenthesize the format string.
-
- When memory buffers are passed as parameters to supply data to build
- objects, as for the \samp{s} and \samp{s\#} formats, the required
- data is copied. Buffers provided by the caller are never referenced
- by the objects created by \cfunction{Py_BuildValue()}. In other
- words, if your code invokes \cfunction{malloc()} and passes the
- allocated memory to \cfunction{Py_BuildValue()}, your code is
- responsible for calling \cfunction{free()} for that memory once
- \cfunction{Py_BuildValue()} returns.
-
- In the following description, the quoted form is the format unit;
- the entry in (round) parentheses is the Python object type that the
- format unit will return; and the entry in [square] brackets is the
- type of the C value(s) to be passed.
-
- The characters space, tab, colon and comma are ignored in format
- strings (but not within format units such as \samp{s\#}). This can
- be used to make long format strings a tad more readable.
-
- \begin{description}
- \item[\samp{s} (string) {[char *]}]
- Convert a null-terminated C string to a Python object. If the C
- string pointer is \NULL, \code{None} is used.
-
- \item[\samp{s\#} (string) {[char *, int]}]
- Convert a C string and its length to a Python object. If the C
- string pointer is \NULL, the length is ignored and \code{None} is
- returned.
-
- \item[\samp{z} (string or \code{None}) {[char *]}]
- Same as \samp{s}.
-
- \item[\samp{z\#} (string or \code{None}) {[char *, int]}]
- Same as \samp{s\#}.
-
- \item[\samp{u} (Unicode string) {[Py_UNICODE *]}]
- Convert a null-terminated buffer of Unicode (UCS-2) data to a
- Python Unicode object. If the Unicode buffer pointer is \NULL,
- \code{None} is returned.
-
- \item[\samp{u\#} (Unicode string) {[Py_UNICODE *, int]}]
- Convert a Unicode (UCS-2) data buffer and its length to a Python
- Unicode object. If the Unicode buffer pointer is \NULL, the
- length is ignored and \code{None} is returned.
-
- \item[\samp{i} (integer) {[int]}]
- Convert a plain C \ctype{int} to a Python integer object.
-
- \item[\samp{b} (integer) {[char]}]
- Same as \samp{i}.
-
- \item[\samp{h} (integer) {[short int]}]
- Same as \samp{i}.
-
- \item[\samp{l} (integer) {[long int]}]
- Convert a C \ctype{long int} to a Python integer object.
-
- \item[\samp{c} (string of length 1) {[char]}]
- Convert a C \ctype{int} representing a character to a Python
- string of length 1.
-
- \item[\samp{d} (float) {[double]}]
- Convert a C \ctype{double} to a Python floating point number.
-
- \item[\samp{f} (float) {[float]}]
- Same as \samp{d}.
-
- \item[\samp{D} (complex) {[Py_complex *]}]
- Convert a C \ctype{Py_complex} structure to a Python complex
- number.
-
- \item[\samp{O} (object) {[PyObject *]}]
- Pass a Python object untouched (except for its reference count,
- which is incremented by one). If the object passed in is a
- \NULL{} pointer, it is assumed that this was caused because the
- call producing the argument found an error and set an exception.
- Therefore, \cfunction{Py_BuildValue()} will return \NULL{} but
- won't raise an exception. If no exception has been raised yet,
- \exception{SystemError} is set.
-
- \item[\samp{S} (object) {[PyObject *]}]
- Same as \samp{O}.
-
- \item[\samp{U} (object) {[PyObject *]}]
- Same as \samp{O}.
-
- \item[\samp{N} (object) {[PyObject *]}]
- Same as \samp{O}, except it doesn't increment the reference count
- on the object. Useful when the object is created by a call to an
- object constructor in the argument list.
-
- \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
- Convert \var{anything} to a Python object through a
- \var{converter} function. The function is called with
- \var{anything} (which should be compatible with \ctype{void *}) as
- its argument and should return a ``new'' Python object, or \NULL{}
- if an error occurred.
-
- \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
- Convert a sequence of C values to a Python tuple with the same
- number of items.
-
- \item[\samp{[\var{items}]} (list) {[\var{matching-items}]}]
- Convert a sequence of C values to a Python list with the same
- number of items.
-
- \item[\samp{\{\var{items}\}} (dictionary) {[\var{matching-items}]}]
- Convert a sequence of C values to a Python dictionary. Each pair
- of consecutive C values adds one item to the dictionary, serving
- as key and value, respectively.
-
- \end{description}
-
- If there is an error in the format string, the
- \exception{SystemError} exception is set and \NULL{} returned.
-\end{cfuncdesc}
diff --git a/Doc/api/veryhigh.tex b/Doc/api/veryhigh.tex
deleted file mode 100644
index e7cb094607..0000000000
--- a/Doc/api/veryhigh.tex
+++ /dev/null
@@ -1,141 +0,0 @@
-\chapter{The Very High Level Layer \label{veryhigh}}
-
-
-The functions in this chapter will let you execute Python source code
-given in a file or a buffer, but they will not let you interact in a
-more detailed way with the interpreter.
-
-Several of these functions accept a start symbol from the grammar as a
-parameter. The available start symbols are \constant{Py_eval_input},
-\constant{Py_file_input}, and \constant{Py_single_input}. These are
-described following the functions which accept them as parameters.
-
-Note also that several of these functions take \ctype{FILE*}
-parameters. On particular issue which needs to be handled carefully
-is that the \ctype{FILE} structure for different C libraries can be
-different and incompatible. Under Windows (at least), it is possible
-for dynamically linked extensions to actually use different libraries,
-so care should be taken that \ctype{FILE*} parameters are only passed
-to these functions if it is certain that they were created by the same
-library that the Python runtime is using.
-
-
-\begin{cfuncdesc}{int}{Py_Main}{int argc, char **argv}
- The main program for the standard interpreter. This is made
- available for programs which embed Python. The \var{argc} and
- \var{argv} parameters should be prepared exactly as those which are
- passed to a C program's \cfunction{main()} function. It is
- important to note that the argument list may be modified (but the
- contents of the strings pointed to by the argument list are not).
- The return value will be the integer passed to the
- \function{sys.exit()} function, \code{1} if the interpreter exits
- due to an exception, or \code{2} if the parameter list does not
- represent a valid Python command line.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, char *filename}
- If \var{fp} refers to a file associated with an interactive device
- (console or terminal input or \UNIX{} pseudo-terminal), return the
- value of \cfunction{PyRun_InteractiveLoop()}, otherwise return the
- result of \cfunction{PyRun_SimpleFile()}. If \var{filename} is
- \NULL, this function uses \code{"???"} as the filename.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyRun_SimpleString}{char *command}
- Executes the Python source code from \var{command} in the
- \module{__main__} module. If \module{__main__} does not already
- exist, it is created. Returns \code{0} on success or \code{-1} if
- an exception was raised. If there was an error, there is no way to
- get the exception information.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyRun_SimpleFile}{FILE *fp, char *filename}
- Similar to \cfunction{PyRun_SimpleString()}, but the Python source
- code is read from \var{fp} instead of an in-memory string.
- \var{filename} should be the name of the file.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyRun_InteractiveOne}{FILE *fp, char *filename}
- Read and execute a single statement from a file associated with an
- interactive device. If \var{filename} is \NULL, \code{"???"} is
- used instead. The user will be prompted using \code{sys.ps1} and
- \code{sys.ps2}. Returns \code{0} when the input was executed
- successfully, \code{-1} if there was an exception, or an error code
- from the \file{errcode.h} include file distributed as part of Python
- if there was a parse error. (Note that \file{errcode.h} is not
- included by \file{Python.h}, so must be included specifically if
- needed.)
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{int}{PyRun_InteractiveLoop}{FILE *fp, char *filename}
- Read and execute statements from a file associated with an
- interactive device until \EOF{} is reached. If \var{filename} is
- \NULL, \code{"???"} is used instead. The user will be prompted
- using \code{sys.ps1} and \code{sys.ps2}. Returns \code{0} at \EOF.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseString}{char *str,
- int start}
- Parse Python source code from \var{str} using the start token
- \var{start}. The result can be used to create a code object which
- can be evaluated efficiently. This is useful if a code fragment
- must be evaluated many times.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{struct _node*}{PyParser_SimpleParseFile}{FILE *fp,
- char *filename, int start}
- Similar to \cfunction{PyParser_SimpleParseString()}, but the Python
- source code is read from \var{fp} instead of an in-memory string.
- \var{filename} should be the name of the file.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyRun_String}{char *str, int start,
- PyObject *globals,
- PyObject *locals}
- Execute Python source code from \var{str} in the context specified
- by the dictionaries \var{globals} and \var{locals}. The parameter
- \var{start} specifies the start token that should be used to parse
- the source code.
-
- Returns the result of executing the code as a Python object, or
- \NULL{} if an exception was raised.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{PyRun_File}{FILE *fp, char *filename,
- int start, PyObject *globals,
- PyObject *locals}
- Similar to \cfunction{PyRun_String()}, but the Python source code is
- read from \var{fp} instead of an in-memory string.
- \var{filename} should be the name of the file.
-\end{cfuncdesc}
-
-\begin{cfuncdesc}{PyObject*}{Py_CompileString}{char *str, char *filename,
- int start}
- Parse and compile the Python source code in \var{str}, returning the
- resulting code object. The start token is given by \var{start};
- this can be used to constrain the code which can be compiled and should
- be \constant{Py_eval_input}, \constant{Py_file_input}, or
- \constant{Py_single_input}. The filename specified by
- \var{filename} is used to construct the code object and may appear
- in tracebacks or \exception{SyntaxError} exception messages. This
- returns \NULL{} if the code cannot be parsed or compiled.
-\end{cfuncdesc}
-
-\begin{cvardesc}{int}{Py_eval_input}
- The start symbol from the Python grammar for isolated expressions;
- for use with
- \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
-\end{cvardesc}
-
-\begin{cvardesc}{int}{Py_file_input}
- The start symbol from the Python grammar for sequences of statements
- as read from a file or other source; for use with
- \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}. This is
- the symbol to use when compiling arbitrarily long Python source code.
-\end{cvardesc}
-
-\begin{cvardesc}{int}{Py_single_input}
- The start symbol from the Python grammar for a single statement; for
- use with \cfunction{Py_CompileString()}\ttindex{Py_CompileString()}.
- This is the symbol used for the interactive interpreter loop.
-\end{cvardesc}
diff --git a/Doc/dist/.cvsignore b/Doc/dist/.cvsignore
deleted file mode 100644
index ea4fca3aac..0000000000
--- a/Doc/dist/.cvsignore
+++ /dev/null
@@ -1,3 +0,0 @@
-*.esis
-*.esis1
-*.xml
diff --git a/Doc/dist/dist.tex b/Doc/dist/dist.tex
deleted file mode 100644
index 91bb228db0..0000000000
--- a/Doc/dist/dist.tex
+++ /dev/null
@@ -1,1883 +0,0 @@
-\documentclass{howto}
-\usepackage{distutils}
-
-% $Id$
-
-% TODO
-% Document extension.read_setup_file
-% Document build_clib command
-%
-
-\title{Distributing Python Modules}
-
-\author{Greg Ward}
-\authoraddress{Email: \email{distutils-sig@python.org}}
-
-\makeindex
-
-\begin{document}
-
-\maketitle
-\begin{abstract}
- \noindent
- This document describes the Python Distribution Utilities
- (``Distutils'') from the module developer's point of view, describing
- how to use the Distutils to make Python modules and extensions easily
- available to a wider audience with very little overhead for
- build/release/install mechanics.
-\end{abstract}
-
-% The ugly "%begin{latexonly}" pseudo-environment supresses the table
-% of contents for HTML generation.
-%
-%begin{latexonly}
-\tableofcontents
-%end{latexonly}
-
-
-\section{Introduction}
-\label{intro}
-
-This document covers using the Distutils to distribute your Python
-modules, concentrating on the role of developer/distributor: if
-you're looking for information on installing Python modules, you
-should refer to the \citetitle[../inst/inst.html]{Installing Python
-Modules} manual.
-
-
-\section{Concepts \& Terminology}
-\label{concepts}
-
-Using the Distutils is quite simple, both for module developers and for
-users/administrators installing third-party modules. As a developer,
-your responsibilities (apart from writing solid, well-documented and
-well-tested code, of course!) are:
-\begin{itemize}
-\item write a setup script (\file{setup.py} by convention)
-\item (optional) write a setup configuration file
-\item create a source distribution
-\item (optional) create one or more built (binary) distributions
-\end{itemize}
-Each of these tasks is covered in this document.
-
-Not all module developers have access to a multitude of platforms, so
-it's not always feasible to expect them to create a multitude of built
-distributions. It is hoped that a class of intermediaries, called
-\emph{packagers}, will arise to address this need. Packagers will take
-source distributions released by module developers, build them on one or
-more platforms, and release the resulting built distributions. Thus,
-users on the most popular platforms will be able to install most popular
-Python module distributions in the most natural way for their platform,
-without having to run a single setup script or compile a line of code.
-
-
-\subsection{A Simple Example}
-\label{simple-example}
-
-The setup script is usually quite simple, although since it's written
-in Python, there are no arbitrary limits to what you can do with it,
-though you should be careful about putting arbitrarily expensive
-operations in your setup script. Unlike, say, Autoconf-style configure
-scripts, the setup script may be run multiple times in the course of
-building and installing your module distribution.
-
-If all you want to do is distribute a module called \module{foo},
-contained in a file \file{foo.py}, then your setup script can be as
-simple as this:
-
-\begin{verbatim}
-from distutils.core import setup
-setup(name="foo",
- version="1.0",
- py_modules=["foo"])
-\end{verbatim}
-
-Some observations:
-\begin{itemize}
-\item most information that you supply to the Distutils is supplied as
- keyword arguments to the \function{setup()} function
-\item those keyword arguments fall into two categories: package
- metadata (name, version number) and information about what's in the
- package (a list of pure Python modules, in this case)
-\item modules are specified by module name, not filename (the same will
- hold true for packages and extensions)
-\item it's recommended that you supply a little more metadata, in
- particular your name, email address and a URL for the project
- (see section~\ref{setup-script} for an example)
-\end{itemize}
-
-To create a source distribution for this module, you would create a
-setup script, \file{setup.py}, containing the above code, and run:
-
-\begin{verbatim}
-python setup.py sdist
-\end{verbatim}
-
-which will create an archive file (e.g., tarball on \UNIX, ZIP file on
-Windows) containing your setup script \file{setup.py}, and your module
-\file{foo.py}. The archive file will be named \file{foo-1.0.tar.gz} (or
-\file{.zip}), and will unpack into a directory \file{foo-1.0}.
-
-If an end-user wishes to install your \module{foo} module, all she has
-to do is download \file{foo-1.0.tar.gz} (or \file{.zip}), unpack it,
-and---from the \file{foo-1.0} directory---run
-
-\begin{verbatim}
-python setup.py install
-\end{verbatim}
-
-which will ultimately copy \file{foo.py} to the appropriate directory
-for third-party modules in their Python installation.
-
-This simple example demonstrates some fundamental concepts of the
-Distutils. First, both developers and installers have the same basic
-user interface, i.e. the setup script. The difference is which
-Distutils \emph{commands} they use: the \command{sdist} command is
-almost exclusively for module developers, while \command{install} is
-more often for installers (although most developers will want to install
-their own code occasionally).
-
-If you want to make things really easy for your users, you can create
-one or more built distributions for them. For instance, if you are
-running on a Windows machine, and want to make things easy for other
-Windows users, you can create an executable installer (the most
-appropriate type of built distribution for this platform) with the
-\command{bdist\_wininst} command. For example:
-
-\begin{verbatim}
-python setup.py bdist_wininst
-\end{verbatim}
-
-will create an executable installer, \file{foo-1.0.win32.exe}, in the
-current directory.
-
-Other useful built distribution formats are RPM, implemented by the
-\command{bdist\_rpm} command, Solaris \program{pkgtool}
-(\command{bdist\_pkgtool}), and HP-UX \program{swinstall}
-(\command{bdist_sdux}). For example, the following command will
-create an RPM file called \file{foo-1.0.noarch.rpm}:
-
-\begin{verbatim}
-python setup.py bdist_rpm
-\end{verbatim}
-
-(The \command{bdist\_rpm} command uses the \command{rpm} executable,
-therefore this has to be run on an RPM-based system such as Red Hat
-Linux, SuSE Linux, or Mandrake Linux.)
-
-You can find out what distribution formats are available at any time by
-running
-
-\begin{verbatim}
-python setup.py bdist --help-formats
-\end{verbatim}
-
-
-\subsection{General Python terminology}
-\label{python-terms}
-
-If you're reading this document, you probably have a good idea of what
-modules, extensions, and so forth are. Nevertheless, just to be sure
-that everyone is operating from a common starting point, we offer the
-following glossary of common Python terms:
-\begin{description}
-\item[module] the basic unit of code reusability in Python: a block of
- code imported by some other code. Three types of modules concern us
- here: pure Python modules, extension modules, and packages.
-
-\item[pure Python module] a module written in Python and contained in a
- single \file{.py} file (and possibly associated \file{.pyc} and/or
- \file{.pyo} files). Sometimes referred to as a ``pure module.''
-
-\item[extension module] a module written in the low-level language of
- the Python implementation: C/C++ for Python, Java for Jython.
- Typically contained in a single dynamically loadable pre-compiled
- file, e.g. a shared object (\file{.so}) file for Python extensions on
- \UNIX, a DLL (given the \file{.pyd} extension) for Python extensions
- on Windows, or a Java class file for Jython extensions. (Note that
- currently, the Distutils only handles C/C++ extensions for Python.)
-
-\item[package] a module that contains other modules; typically contained
- in a directory in the filesystem and distinguished from other
- directories by the presence of a file \file{\_\_init\_\_.py}.
-
-\item[root package] the root of the hierarchy of packages. (This isn't
- really a package, since it doesn't have an \file{\_\_init\_\_.py}
- file. But we have to call it something.) The vast majority of the
- standard library is in the root package, as are many small, standalone
- third-party modules that don't belong to a larger module collection.
- Unlike regular packages, modules in the root package can be found in
- many directories: in fact, every directory listed in \code{sys.path}
- contributes modules to the root package.
-\end{description}
-
-
-\subsection{Distutils-specific terminology}
-\label{distutils-term}
-
-The following terms apply more specifically to the domain of
-distributing Python modules using the Distutils:
-\begin{description}
-\item[module distribution] a collection of Python modules distributed
- together as a single downloadable resource and meant to be installed
- \emph{en masse}. Examples of some well-known module distributions are
- Numeric Python, PyXML, PIL (the Python Imaging Library), or
- mxBase. (This would be called a \emph{package}, except that term
- is already taken in the Python context: a single module distribution
- may contain zero, one, or many Python packages.)
-
-\item[pure module distribution] a module distribution that contains only
- pure Python modules and packages. Sometimes referred to as a ``pure
- distribution.''
-
-\item[non-pure module distribution] a module distribution that contains
- at least one extension module. Sometimes referred to as a ``non-pure
- distribution.''
-
-\item[distribution root] the top-level directory of your source tree (or
- source distribution); the directory where \file{setup.py} exists. Generally
- \file{setup.py} will be run from this directory.
-\end{description}
-
-
-\section{Writing the Setup Script}
-\label{setup-script}
-
-The setup script is the centre of all activity in building,
-distributing, and installing modules using the Distutils. The main
-purpose of the setup script is to describe your module distribution to
-the Distutils, so that the various commands that operate on your modules
-do the right thing. As we saw in section~\ref{simple-example} above,
-the setup script consists mainly of a call to \function{setup()}, and
-most information supplied to the Distutils by the module developer is
-supplied as keyword arguments to \function{setup()}.
-
-Here's a slightly more involved example, which we'll follow for the next
-couple of sections: the Distutils' own setup script. (Keep in mind that
-although the Distutils are included with Python 1.6 and later, they also
-have an independent existence so that Python 1.5.2 users can use them to
-install other module distributions. The Distutils' own setup script,
-shown here, is used to install the package into Python 1.5.2.)
-
-\begin{verbatim}
-#!/usr/bin/env python
-
-from distutils.core import setup
-
-setup(name="Distutils",
- version="1.0",
- description="Python Distribution Utilities",
- author="Greg Ward",
- author_email="gward@python.net",
- url="http://www.python.org/sigs/distutils-sig/",
- packages=['distutils', 'distutils.command'],
- )
-\end{verbatim}
-
-There are only two differences between this and the trivial one-file
-distribution presented in section~\ref{simple-example}: more
-metadata, and the specification of pure Python modules by package,
-rather than by module. This is important since the Distutils consist of
-a couple of dozen modules split into (so far) two packages; an explicit
-list of every module would be tedious to generate and difficult to
-maintain. For more information on the additional meta-data, see
-section~\ref{meta-data}.
-
-Note that any pathnames (files or directories) supplied in the setup
-script should be written using the \UNIX{} convention, i.e.
-slash-separated. The Distutils will take care of converting this
-platform-neutral representation into whatever is appropriate on your
-current platform before actually using the pathname. This makes your
-setup script portable across operating systems, which of course is one
-of the major goals of the Distutils. In this spirit, all pathnames in
-this document are slash-separated. (MacOS programmers should keep in
-mind that the \emph{absence} of a leading slash indicates a relative
-path, the opposite of the MacOS convention with colons.)
-
-This, of course, only applies to pathnames given to Distutils
-functions. If you, for example, use standard Python functions such as
-\function{glob.glob()} or \function{os.listdir()} to specify files, you
-should be careful to write portable code instead of hardcoding path
-separators:
-
-\begin{verbatim}
- glob.glob(os.path.join('mydir', 'subdir', '*.html'))
- os.listdir(os.path.join('mydir', 'subdir'))
-\end{verbatim}
-
-
-\subsection{Listing whole packages}
-\label{listing-packages}
-
-The \option{packages} option tells the Distutils to process (build,
-distribute, install, etc.) all pure Python modules found in each package
-mentioned in the \option{packages} list. In order to do this, of
-course, there has to be a correspondence between package names and
-directories in the filesystem. The default correspondence is the most
-obvious one, i.e. package \module{distutils} is found in the directory
-\file{distutils} relative to the distribution root. Thus, when you say
-\code{packages = ['foo']} in your setup script, you are promising that
-the Distutils will find a file \file{foo/\_\_init\_\_.py} (which might
-be spelled differently on your system, but you get the idea) relative to
-the directory where your setup script lives. If you break this
-promise, the Distutils will issue a warning but still process the broken
-package anyways.
-
-If you use a different convention to lay out your source directory,
-that's no problem: you just have to supply the \option{package\_dir}
-option to tell the Distutils about your convention. For example, say
-you keep all Python source under \file{lib}, so that modules in the
-``root package'' (i.e., not in any package at all) are in
-\file{lib}, modules in the \module{foo} package are in \file{lib/foo},
-and so forth. Then you would put
-
-\begin{verbatim}
-package_dir = {'': 'lib'}
-\end{verbatim}
-
-in your setup script. The keys to this dictionary are package names,
-and an empty package name stands for the root package. The values are
-directory names relative to your distribution root. In this case, when
-you say \code{packages = ['foo']}, you are promising that the file
-\file{lib/foo/\_\_init\_\_.py} exists.
-
-Another possible convention is to put the \module{foo} package right in
-\file{lib}, the \module{foo.bar} package in \file{lib/bar}, etc. This
-would be written in the setup script as
-
-\begin{verbatim}
-package_dir = {'foo': 'lib'}
-\end{verbatim}
-
-A \code{\var{package}: \var{dir}} entry in the \option{package\_dir}
-dictionary implicitly applies to all packages below \var{package}, so
-the \module{foo.bar} case is automatically handled here. In this
-example, having \code{packages = ['foo', 'foo.bar']} tells the Distutils
-to look for \file{lib/\_\_init\_\_.py} and
-\file{lib/bar/\_\_init\_\_.py}. (Keep in mind that although
-\option{package\_dir} applies recursively, you must explicitly list all
-packages in \option{packages}: the Distutils will \emph{not} recursively
-scan your source tree looking for any directory with an
-\file{\_\_init\_\_.py} file.)
-
-
-\subsection{Listing individual modules}
-\label{listing-modules}
-
-For a small module distribution, you might prefer to list all modules
-rather than listing packages---especially the case of a single module
-that goes in the ``root package'' (i.e., no package at all). This
-simplest case was shown in section~\ref{simple-example}; here is a
-slightly more involved example:
-
-\begin{verbatim}
-py_modules = ['mod1', 'pkg.mod2']
-\end{verbatim}
-
-This describes two modules, one of them in the ``root'' package, the
-other in the \module{pkg} package. Again, the default package/directory
-layout implies that these two modules can be found in \file{mod1.py} and
-\file{pkg/mod2.py}, and that \file{pkg/\_\_init\_\_.py} exists as well.
-And again, you can override the package/directory correspondence using
-the \option{package\_dir} option.
-
-
-\subsection{Describing extension modules}
-\label{describing-extensions}
-
-% XXX read over this section
-Just as writing Python extension modules is a bit more complicated than
-writing pure Python modules, describing them to the Distutils is a bit
-more complicated. Unlike pure modules, it's not enough just to list
-modules or packages and expect the Distutils to go out and find the
-right files; you have to specify the extension name, source file(s), and
-any compile/link requirements (include directories, libraries to link
-with, etc.).
-
-All of this is done through another keyword argument to
-\function{setup()}, the \option{extensions} option. \option{extensions}
-is just a list of \class{Extension} instances, each of which describes a
-single extension module. Suppose your distribution includes a single
-extension, called \module{foo} and implemented by \file{foo.c}. If no
-additional instructions to the compiler/linker are needed, describing
-this extension is quite simple:
-
-\begin{verbatim}
-uExtension("foo", ["foo.c"])
-\end{verbatim}
-
-The \class{Extension} class can be imported from
-\module{distutils.core} along with \function{setup()}. Thus, the setup
-script for a module distribution that contains only this one extension
-and nothing else might be:
-
-\begin{verbatim}
-from distutils.core import setup, Extension
-setup(name="foo", version="1.0",
- ext_modules=[Extension("foo", ["foo.c"])])
-\end{verbatim}
-
-The \class{Extension} class (actually, the underlying extension-building
-machinery implemented by the \command{build\_ext} command) supports a
-great deal of flexibility in describing Python extensions, which is
-explained in the following sections.
-
-
-\subsubsection{Extension names and packages}
-
-The first argument to the \class{Extension} constructor is always the
-name of the extension, including any package names. For example,
-
-\begin{verbatim}
-Extension("foo", ["src/foo1.c", "src/foo2.c"])
-\end{verbatim}
-
-describes an extension that lives in the root package, while
-
-\begin{verbatim}
-Extension("pkg.foo", ["src/foo1.c", "src/foo2.c"])
-\end{verbatim}
-
-describes the same extension in the \module{pkg} package. The source
-files and resulting object code are identical in both cases; the only
-difference is where in the filesystem (and therefore where in Python's
-namespace hierarchy) the resulting extension lives.
-
-If you have a number of extensions all in the same package (or all under
-the same base package), use the \option{ext\_package} keyword argument
-to \function{setup()}. For example,
-
-\begin{verbatim}
-setup(...
- ext_package="pkg",
- ext_modules=[Extension("foo", ["foo.c"]),
- Extension("subpkg.bar", ["bar.c"])]
- )
-\end{verbatim}
-
-will compile \file{foo.c} to the extension \module{pkg.foo}, and
-\file{bar.c} to \module{pkg.subpkg.bar}.
-
-
-\subsubsection{Extension source files}
-
-The second argument to the \class{Extension} constructor is a list of
-source files. Since the Distutils currently only support C, \Cpp, and
-Objective-C extensions, these are normally C/\Cpp/Objective-C source
-files. (Be sure to use appropriate extensions to distinguish \Cpp\
-source files: \file{.cc} and \file{.cpp} seem to be recognized by both
-\UNIX{} and Windows compilers.)
-
-However, you can also include SWIG interface (\file{.i}) files in the
-list; the \command{build\_ext} command knows how to deal with SWIG
-extensions: it will run SWIG on the interface file and compile the
-resulting C/C++ file into your extension.
-
-\XXX{SWIG support is rough around the edges and largely untested;
- especially SWIG support of C++ extensions! Explain in more detail
- here when the interface firms up.}
-
-On some platforms, you can include non-source files that are processed
-by the compiler and included in your extension. Currently, this just
-means Windows message text (\file{.mc}) files and resource definition
-(\file{.rc}) files for Visual C++. These will be compiled to binary resource
-(\file{.res}) files and linked into the executable.
-
-
-\subsubsection{Preprocessor options}
-
-Three optional arguments to \class{Extension} will help if you need to
-specify include directories to search or preprocessor macros to
-define/undefine: \code{include\_dirs}, \code{define\_macros}, and
-\code{undef\_macros}.
-
-For example, if your extension requires header files in the
-\file{include} directory under your distribution root, use the
-\code{include\_dirs} option:
-
-\begin{verbatim}
-Extension("foo", ["foo.c"], include_dirs=["include"])
-\end{verbatim}
-
-You can specify absolute directories there; if you know that your
-extension will only be built on \UNIX{} systems with X11R6 installed to
-\file{/usr}, you can get away with
-
-\begin{verbatim}
-Extension("foo", ["foo.c"], include_dirs=["/usr/include/X11"])
-\end{verbatim}
-
-You should avoid this sort of non-portable usage if you plan to
-distribute your code: it's probably better to write C code like
-\begin{verbatim}
-#include
-\end{verbatim}
-
-If you need to include header files from some other Python extension,
-you can take advantage of the fact that header files are installed in a
-consistent way by the Distutils \command{install\_header} command. For
-example, the Numerical Python header files are installed (on a standard
-Unix installation) to \file{/usr/local/include/python1.5/Numerical}.
-(The exact location will differ according to your platform and Python
-installation.) Since the Python include
-directory---\file{/usr/local/include/python1.5} in this case---is always
-included in the search path when building Python extensions, the best
-approach is to write C code like
-\begin{verbatim}
-#include
-\end{verbatim}
-If you must put the \file{Numerical} include directory right into your
-header search path, though, you can find that directory using the
-Distutils \module{sysconfig} module:
-
-\begin{verbatim}
-from distutils.sysconfig import get_python_inc
-incdir = os.path.join(get_python_inc(plat_specific=1), "Numerical")
-setup(...,
- Extension(..., include_dirs=[incdir]))
-\end{verbatim}
-
-Even though this is quite portable---it will work on any Python
-installation, regardless of platform---it's probably easier to just
-write your C code in the sensible way.
-
-You can define and undefine pre-processor macros with the
-\code{define\_macros} and \code{undef\_macros} options.
-\code{define\_macros} takes a list of \code{(name, value)} tuples, where
-\code{name} is the name of the macro to define (a string) and
-\code{value} is its value: either a string or \code{None}. (Defining a
-macro \code{FOO} to \code{None} is the equivalent of a bare
-\code{\#define FOO} in your C source: with most compilers, this sets
-\code{FOO} to the string \code{1}.) \code{undef\_macros} is just
-a list of macros to undefine.
-
-For example:
-
-\begin{verbatim}
-Extension(...,
- define_macros=[('NDEBUG', '1')],
- ('HAVE_STRFTIME', None),
- undef_macros=['HAVE_FOO', 'HAVE_BAR'])
-\end{verbatim}
-
-is the equivalent of having this at the top of every C source file:
-
-\begin{verbatim}
-#define NDEBUG 1
-#define HAVE_STRFTIME
-#undef HAVE_FOO
-#undef HAVE_BAR
-\end{verbatim}
-
-
-\subsubsection{Library options}
-
-You can also specify the libraries to link against when building your
-extension, and the directories to search for those libraries. The
-\code{libraries} option is a list of libraries to link against,
-\code{library\_dirs} is a list of directories to search for libraries at
-link-time, and \code{runtime\_library\_dirs} is a list of directories to
-search for shared (dynamically loaded) libraries at run-time.
-
-For example, if you need to link against libraries known to be in the
-standard library search path on target systems
-
-\begin{verbatim}
-Extension(...,
- libraries=["gdbm", "readline"])
-\end{verbatim}
-
-If you need to link with libraries in a non-standard location, you'll
-have to include the location in \code{library\_dirs}:
-
-\begin{verbatim}
-Extension(...,
- library_dirs=["/usr/X11R6/lib"],
- libraries=["X11", "Xt"])
-\end{verbatim}
-
-(Again, this sort of non-portable construct should be avoided if you
-intend to distribute your code.)
-
-\XXX{Should mention clib libraries here or somewhere else!}
-
-\subsubsection{Other options}
-
-There are still some other options which can be used to handle special
-cases.
-
-The \option{extra\_objects} option is a list of object files to be passed
-to the linker. These files must not have extensions, as the default
-extension for the compiler is used.
-
-\option{extra\_compile\_args} and \option{extra\_link\_args} can be used
-to specify additional command line options for the respective compiler and
-linker command lines.
-
-\option{export\_symbols} is only useful on Windows. It can contain a list
-of symbols (functions or variables) to be exported. This option
-is not needed when building compiled extensions: Distutils
-will automatically add \code{initmodule}
-to the list of exported symbols.
-
-\subsection{Installing Scripts}
-So far we have been dealing with pure and non-pure Python modules,
-which are usually not run by themselves but imported by scripts.
-
-Scripts are files containing Python source code, intended to be
-started from the command line. Scripts don't require Distutils to do
-anything very complicated. The only clever feature is that if the
-first line of the script starts with \code{\#!} and contains the word
-``python'', the Distutils will adjust the first line to refer to the
-current interpreter location.
-
-The \option{scripts} option simply is a list of files to be handled
-in this way. From the PyXML setup script:
-
-\begin{verbatim}
-setup (...
- scripts = ['scripts/xmlproc_parse', 'scripts/xmlproc_val']
- )
-\end{verbatim}
-
-
-\subsection{Installing Additional Files}
-
-The \option{data\_files} option can be used to specify additional
-files needed by the module distribution: configuration files, message
-catalogs, data files, anything which doesn't fit in the previous
-categories.
-
-\option{data\_files} specifies a sequence of (\var{directory},
-\var{files}) pairs in the following way:
-
-\begin{verbatim}
-setup(...
- data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),
- ('config', ['cfg/data.cfg']),
- ('/etc/init.d', ['init-script'])]
- )
-\end{verbatim}
-
-Note that you can specify the directory names where the data files
-will be installed, but you cannot rename the data files themselves.
-
-Each (\var{directory}, \var{files}) pair in the sequence specifies the
-installation directory and the files to install there. If
-\var{directory} is a relative path, it is interpreted relative to the
-installation prefix (Python's \code{sys.prefix} for pure-Python
-packages, \code{sys.exec_prefix} for packages that contain extension
-modules). Each file name in \var{files} is interpreted relative to
-the \file{setup.py} script at the top of the package source
-distribution. No directory information from \var{files} is used to
-determine the final location of the installed file; only the name of
-the file is used.
-
-You can specify the \option{data\_files} options as a simple sequence
-of files without specifying a target directory, but this is not recommended,
-and the \command{install} command will print a warning in this case.
-To install data files directly in the target directory, an empty
-string should be given as the directory.
-
-\subsection{Additional meta-data}
-\label{meta-data}
-
-The setup script may include additional meta-data beyond the name and
-version. This information includes:
-
-\begin{tableiv}{l|l|l|c}{code}%
- {Meta-Data}{Description}{Value}{Notes}
- \lineiv{name}{name of the package}
- {short string}{(1)}
- \lineiv{version}{version of this release}
- {short string}{(1)(2)}
- \lineiv{author}{package author's name}
- {short string}{(3)}
- \lineiv{author_email}{email address of the package author}
- {email address}{(3)}
- \lineiv{maintainer}{package maintainer's name}
- {short string}{(3)}
- \lineiv{maintainer_email}{email address of the package maintainer}
- {email address}{(3)}
- \lineiv{url}{home page for the package}
- {URL}{(1)}
- \lineiv{description}{short, summary description of the package}
- {short string}{}
- \lineiv{long_description}{longer description of the package}
- {long string}{}
- \lineiv{download_url}{location where the package may be downloaded}
- {URL}{(4)}
- \lineiv{classifiers}{a list of Trove classifiers}
- {list of strings}{(4)}
-\end{tableiv}
-
-\noindent Notes:
-\begin{description}
-\item[(1)] These fields are required.
-\item[(2)] It is recommended that versions take the form
- \emph{major.minor\optional{.patch\optional{.sub}}}.
-\item[(3)] Either the author or the maintainer must be identified.
-\item[(4)] These fields should not be used if your package is to be
- compatible with Python versions prior to 2.2.3 or 2.3. The list is
- available from the \ulink{PyPI website}{http://www.python.org/pypi}.
-
-\item["short string"] A single line of text, not more than 200 characters.
-\item["long string"] Multiple lines of plain text in ReStructuredText
- format (see \url{http://docutils.sf.net/}).
-\item["list of strings"] See below.
-\end{description}
-
-None of the string values may be Unicode.
-
-Encoding the version information is an art in itself. Python packages
-generally adhere to the version format
-\emph{major.minor\optional{.patch}\optional{sub}}. The major number is
-0 for
-initial, experimental releases of software. It is incremented for
-releases that represent major milestones in a package. The minor
-number is incremented when important new features are added to the
-package. The patch number increments when bug-fix releases are
-made. Additional trailing version information is sometimes used to
-indicate sub-releases. These are "a1,a2,...,aN" (for alpha releases,
-where functionality and API may change), "b1,b2,...,bN" (for beta
-releases, which only fix bugs) and "pr1,pr2,...,prN" (for final
-pre-release release testing). Some examples:
-
-\begin{description}
-\item[0.1.0] the first, experimental release of a package
-\item[1.0.1a2] the second alpha release of the first patch version of 1.0
-\end{description}
-
-\option{classifiers} are specified in a python list:
-
-\begin{verbatim}
-setup(...
- classifiers = [
- 'Development Status :: 4 - Beta',
- 'Environment :: Console',
- 'Environment :: Web Environment',
- 'Intended Audience :: End Users/Desktop',
- 'Intended Audience :: Developers',
- 'Intended Audience :: System Administrators',
- 'License :: OSI Approved :: Python Software Foundation License',
- 'Operating System :: MacOS :: MacOS X',
- 'Operating System :: Microsoft :: Windows',
- 'Operating System :: POSIX',
- 'Programming Language :: Python',
- 'Topic :: Communications :: Email',
- 'Topic :: Office/Business',
- 'Topic :: Software Development :: Bug Tracking',
- ],
- )
-\end{verbatim}
-
-If you wish to include classifiers in your \file{setup.py} file and also
-wish to remain backwards-compatible with Python releases prior to 2.2.3,
-then you can include the following code fragment in your \file{setup.py}
-before the \code{setup()} call.
-
-\begin{verbatim}
-# patch distutils if it can't cope with the "classifiers" or
-# "download_url" keywords
-if sys.version < '2.2.3':
- from distutils.dist import DistributionMetadata
- DistributionMetadata.classifiers = None
- DistributionMetadata.download_url = None
-\end{verbatim}
-
-
-\section{Writing the Setup Configuration File}
-\label{setup-config}
-
-Often, it's not possible to write down everything needed to build a
-distribution \emph{a priori}: you may need to get some information from
-the user, or from the user's system, in order to proceed. As long as
-that information is fairly simple---a list of directories to search for
-C header files or libraries, for example---then providing a
-configuration file, \file{setup.cfg}, for users to edit is a cheap and
-easy way to solicit it. Configuration files also let you provide
-default values for any command option, which the installer can then
-override either on the command-line or by editing the config file.
-
-% (If you have more advanced needs, such as determining which extensions
-% to build based on what capabilities are present on the target system,
-% then you need the Distutils ``auto-configuration'' facility. This
-% started to appear in Distutils 0.9 but, as of this writing, isn't mature
-% or stable enough yet for real-world use.)
-
-The setup configuration file is a useful middle-ground between the setup
-script---which, ideally, would be opaque to installers\footnote{This
- ideal probably won't be achieved until auto-configuration is fully
- supported by the Distutils.}---and the command-line to the setup
-script, which is outside of your control and entirely up to the
-installer. In fact, \file{setup.cfg} (and any other Distutils
-configuration files present on the target system) are processed after
-the contents of the setup script, but before the command-line. This has
-several useful consequences:
-\begin{itemize}
-\item installers can override some of what you put in \file{setup.py} by
- editing \file{setup.cfg}
-\item you can provide non-standard defaults for options that are not
- easily set in \file{setup.py}
-\item installers can override anything in \file{setup.cfg} using the
- command-line options to \file{setup.py}
-\end{itemize}
-
-The basic syntax of the configuration file is simple:
-
-\begin{verbatim}
-[command]
-option=value
-...
-\end{verbatim}
-
-where \var{command} is one of the Distutils commands (e.g.
-\command{build\_py}, \command{install}), and \var{option} is one of
-the options that command supports. Any number of options can be
-supplied for each command, and any number of command sections can be
-included in the file. Blank lines are ignored, as are comments, which
-run from a \character{\#} character until the end of the line. Long
-option values can be split across multiple lines simply by indenting
-the continuation lines.
-
-You can find out the list of options supported by a particular command
-with the universal \longprogramopt{help} option, e.g.
-
-\begin{verbatim}
-> python setup.py --help build_ext
-[...]
-Options for 'build_ext' command:
- --build-lib (-b) directory for compiled extension modules
- --build-temp (-t) directory for temporary files (build by-products)
- --inplace (-i) ignore build-lib and put compiled extensions into the
- source directory alongside your pure Python modules
- --include-dirs (-I) list of directories to search for header files
- --define (-D) C preprocessor macros to define
- --undef (-U) C preprocessor macros to undefine
-[...]
-\end{verbatim}
-
-Note that an option spelled \longprogramopt{foo-bar} on the command-line
-is spelled \option{foo\_bar} in configuration files.
-
-For example, say you want your extensions to be built
-``in-place''---that is, you have an extension \module{pkg.ext}, and you
-want the compiled extension file (\file{ext.so} on \UNIX, say) to be put
-in the same source directory as your pure Python modules
-\module{pkg.mod1} and \module{pkg.mod2}. You can always use the
-\longprogramopt{inplace} option on the command-line to ensure this:
-
-\begin{verbatim}
-python setup.py build_ext --inplace
-\end{verbatim}
-
-But this requires that you always specify the \command{build\_ext}
-command explicitly, and remember to provide \longprogramopt{inplace}.
-An easier way is to ``set and forget'' this option, by encoding it in
-\file{setup.cfg}, the configuration file for this distribution:
-
-\begin{verbatim}
-[build_ext]
-inplace=1
-\end{verbatim}
-
-This will affect all builds of this module distribution, whether or not
-you explcitly specify \command{build\_ext}. If you include
-\file{setup.cfg} in your source distribution, it will also affect
-end-user builds---which is probably a bad idea for this option, since
-always building extensions in-place would break installation of the
-module distribution. In certain peculiar cases, though, modules are
-built right in their installation directory, so this is conceivably a
-useful ability. (Distributing extensions that expect to be built in
-their installation directory is almost always a bad idea, though.)
-
-Another example: certain commands take a lot of options that don't
-change from run to run; for example, \command{bdist\_rpm} needs to know
-everything required to generate a ``spec'' file for creating an RPM
-distribution. Some of this information comes from the setup script, and
-some is automatically generated by the Distutils (such as the list of
-files installed). But some of it has to be supplied as options to
-\command{bdist\_rpm}, which would be very tedious to do on the
-command-line for every run. Hence, here is a snippet from the
-Distutils' own \file{setup.cfg}:
-
-\begin{verbatim}
-[bdist_rpm]
-release = 1
-packager = Greg Ward
-doc_files = CHANGES.txt
- README.txt
- USAGE.txt
- doc/
- examples/
-\end{verbatim}
-
-Note that the \option{doc\_files} option is simply a
-whitespace-separated string split across multiple lines for readability.
-
-
-\begin{seealso}
- \seetitle[../inst/config-syntax.html]{Installing Python
- Modules}{More information on the configuration files is
- available in the manual for system administrators.}
-\end{seealso}
-
-
-\section{Creating a Source Distribution}
-\label{source-dist}
-
-As shown in section~\ref{simple-example}, you use the
-\command{sdist} command to create a source distribution. In the
-simplest case,
-
-\begin{verbatim}
-python setup.py sdist
-\end{verbatim}
-
-(assuming you haven't specified any \command{sdist} options in the setup
-script or config file), \command{sdist} creates the archive of the
-default format for the current platform. The default format is a gzip'ed
-tar file (\file{.tar.gz}) on \UNIX, and ZIP file on Windows.
-\XXX{no MacOS support here}
-
-You can specify as many formats as you like using the
-\longprogramopt{formats} option, for example:
-
-\begin{verbatim}
-python setup.py sdist --formats=gztar,zip
-\end{verbatim}
-
-to create a gzipped tarball and a zip file. The available formats are:
-\begin{tableiii}{l|l|c}{code}%
- {Format}{Description}{Notes}
- \lineiii{zip}{zip file (\file{.zip})}{(1),(3)}
- \lineiii{gztar}{gzip'ed tar file (\file{.tar.gz})}{(2),(4)}
- \lineiii{bztar}{bzip2'ed tar file (\file{.tar.bz2})}{(4)}
- \lineiii{ztar}{compressed tar file (\file{.tar.Z})}{(4)}
- \lineiii{tar}{tar file (\file{.tar})}{(4)}
-\end{tableiii}
-
-\noindent Notes:
-\begin{description}
-\item[(1)] default on Windows
-\item[(2)] default on \UNIX
-\item[(3)] requires either external \program{zip} utility or
- \module{zipfile} module (part of the standard Python library since
- Python~1.6)
-\item[(4)] requires external utilities: \program{tar} and possibly one
- of \program{gzip}, \program{bzip2}, or \program{compress}
-\end{description}
-
-
-
-\subsection{Specifying the files to distribute}
-\label{manifest}
-
-If you don't supply an explicit list of files (or instructions on how to
-generate one), the \command{sdist} command puts a minimal default set
-into the source distribution:
-\begin{itemize}
-\item all Python source files implied by the \option{py\_modules} and
- \option{packages} options
-\item all C source files mentioned in the \option{ext\_modules} or
- \option{libraries} options (\XXX{getting C library sources currently
- broken -- no get\_source\_files() method in build\_clib.py!})
-\item anything that looks like a test script: \file{test/test*.py}
- (currently, the Distutils don't do anything with test scripts except
- include them in source distributions, but in the future there will be
- a standard for testing Python module distributions)
-\item \file{README.txt} (or \file{README}), \file{setup.py} (or whatever
- you called your setup script), and \file{setup.cfg}
-\end{itemize}
-
-Sometimes this is enough, but usually you will want to specify
-additional files to distribute. The typical way to do this is to write
-a \emph{manifest template}, called \file{MANIFEST.in} by default. The
-manifest template is just a list of instructions for how to generate
-your manifest file, \file{MANIFEST}, which is the exact list of files to
-include in your source distribution. The \command{sdist} command
-processes this template and generates a manifest based on its
-instructions and what it finds in the filesystem.
-
-If you prefer to roll your own manifest file, the format is simple: one
-filename per line, regular files (or symlinks to them) only. If you do
-supply your own \file{MANIFEST}, you must specify everything: the
-default set of files described above does not apply in this case.
-
-The manifest template has one command per line, where each command
-specifies a set of files to include or exclude from the source
-distribution. For an example, again we turn to the Distutils' own
-manifest template:
-
-\begin{verbatim}
-include *.txt
-recursive-include examples *.txt *.py
-prune examples/sample?/build
-\end{verbatim}
-
-The meanings should be fairly clear: include all files in the
-distribution root matching \code{*.txt}, all files anywhere under the
-\file{examples} directory matching \code{*.txt} or \code{*.py}, and
-exclude all directories matching \code{examples/sample?/build}. All of
-this is done \emph{after} the standard include set, so you can exclude
-files from the standard set with explicit instructions in the manifest
-template. (Or, you can use the \longprogramopt{no-defaults} option to
-disable the standard set entirely.) There are several other commands
-available in the manifest template mini-language; see
-section~\ref{sdist-cmd}.
-
-The order of commands in the manifest template matters: initially, we
-have the list of default files as described above, and each command in
-the template adds to or removes from that list of files. Once we have
-fully processed the manifest template, we remove files that should not
-be included in the source distribution:
-\begin{itemize}
-\item all files in the Distutils ``build'' tree (default \file{build/})
-\item all files in directories named \file{RCS} or \file{CVS}
-\end{itemize}
-Now we have our complete list of files, which is written to the manifest
-for future reference, and then used to build the source distribution
-archive(s).
-
-You can disable the default set of included files with the
-\longprogramopt{no-defaults} option, and you can disable the standard
-exclude set with \longprogramopt{no-prune}.
-
-Following the Distutils' own manifest template, let's trace how the
-\command{sdist} command builds the list of files to include in the
-Distutils source distribution:
-\begin{enumerate}
-\item include all Python source files in the \file{distutils} and
- \file{distutils/command} subdirectories (because packages
- corresponding to those two directories were mentioned in the
- \option{packages} option in the setup script---see
- section~\ref{setup-script})
-\item include \file{README.txt}, \file{setup.py}, and \file{setup.cfg}
- (standard files)
-\item include \file{test/test*.py} (standard files)
-\item include \file{*.txt} in the distribution root (this will find
- \file{README.txt} a second time, but such redundancies are weeded out
- later)
-\item include anything matching \file{*.txt} or \file{*.py} in the
- sub-tree under \file{examples},
-\item exclude all files in the sub-trees starting at directories
- matching \file{examples/sample?/build}---this may exclude files
- included by the previous two steps, so it's important that the
- \code{prune} command in the manifest template comes after the
- \code{recursive-include} command
-\item exclude the entire \file{build} tree, and any \file{RCS} or
- \file{CVS} directories
-\end{enumerate}
-Just like in the setup script, file and directory names in the manifest
-template should always be slash-separated; the Distutils will take care
-of converting them to the standard representation on your platform.
-That way, the manifest template is portable across operating systems.
-
-
-\subsection{Manifest-related options}
-\label{manifest-options}
-
-The normal course of operations for the \command{sdist} command is as
-follows:
-\begin{itemize}
-\item if the manifest file, \file{MANIFEST} doesn't exist, read
- \file{MANIFEST.in} and create the manifest
-\item if neither \file{MANIFEST} nor \file{MANIFEST.in} exist, create a
- manifest with just the default file set
-\item if either \file{MANIFEST.in} or the setup script (\file{setup.py})
- are more recent than \file{MANIFEST}, recreate \file{MANIFEST} by
- reading \file{MANIFEST.in}
-\item use the list of files now in \file{MANIFEST} (either just
- generated or read in) to create the source distribution archive(s)
-\end{itemize}
-There are a couple of options that modify this behaviour. First, use
-the \longprogramopt{no-defaults} and \longprogramopt{no-prune} to
-disable the standard ``include'' and ``exclude'' sets.
-
-Second, you might want to force the manifest to be regenerated---for
-example, if you have added or removed files or directories that match an
-existing pattern in the manifest template, you should regenerate the
-manifest:
-
-\begin{verbatim}
-python setup.py sdist --force-manifest
-\end{verbatim}
-
-Or, you might just want to (re)generate the manifest, but not create a
-source distribution:
-
-\begin{verbatim}
-python setup.py sdist --manifest-only
-\end{verbatim}
-
-\longprogramopt{manifest-only} implies \longprogramopt{force-manifest}.
-\programopt{-o} is a shortcut for \longprogramopt{manifest-only}, and
-\programopt{-f} for \longprogramopt{force-manifest}.
-
-
-\section{Creating Built Distributions}
-\label{built-dist}
-
-A ``built distribution'' is what you're probably used to thinking of
-either as a ``binary package'' or an ``installer'' (depending on your
-background). It's not necessarily binary, though, because it might
-contain only Python source code and/or byte-code; and we don't call it a
-package, because that word is already spoken for in Python. (And
-``installer'' is a term specific to the Windows world. \XXX{do Mac
- people use it?})
-
-A built distribution is how you make life as easy as possible for
-installers of your module distribution: for users of RPM-based Linux
-systems, it's a binary RPM; for Windows users, it's an executable
-installer; for Debian-based Linux users, it's a Debian package; and so
-forth. Obviously, no one person will be able to create built
-distributions for every platform under the sun, so the Distutils are
-designed to enable module developers to concentrate on their
-specialty---writing code and creating source distributions---while an
-intermediary species called \emph{packagers} springs up to turn source
-distributions into built distributions for as many platforms as there
-are packagers.
-
-Of course, the module developer could be his own packager; or the
-packager could be a volunteer ``out there'' somewhere who has access to
-a platform which the original developer does not; or it could be
-software periodically grabbing new source distributions and turning them
-into built distributions for as many platforms as the software has
-access to. Regardless of who they are, a packager uses the
-setup script and the \command{bdist} command family to generate built
-distributions.
-
-As a simple example, if I run the following command in the Distutils
-source tree:
-
-\begin{verbatim}
-python setup.py bdist
-\end{verbatim}
-
-then the Distutils builds my module distribution (the Distutils itself
-in this case), does a ``fake'' installation (also in the \file{build}
-directory), and creates the default type of built distribution for my
-platform. The default format for built distributions is a ``dumb'' tar
-file on \UNIX, and a simple executable installer on Windows. (That tar
-file is considered ``dumb'' because it has to be unpacked in a specific
-location to work.)
-
-Thus, the above command on a \UNIX{} system creates
-\file{Distutils-1.0.\filevar{plat}.tar.gz}; unpacking this tarball
-from the right place installs the Distutils just as though you had
-downloaded the source distribution and run \code{python setup.py
- install}. (The ``right place'' is either the root of the filesystem or
-Python's \filevar{prefix} directory, depending on the options given to
-the \command{bdist\_dumb} command; the default is to make dumb
-distributions relative to \filevar{prefix}.)
-
-Obviously, for pure Python distributions, this isn't any simpler than
-just running \code{python setup.py install}---but for non-pure
-distributions, which include extensions that would need to be
-compiled, it can mean the difference between someone being able to use
-your extensions or not. And creating ``smart'' built distributions,
-such as an RPM package or an executable installer for Windows, is far
-more convenient for users even if your distribution doesn't include
-any extensions.
-
-The \command{bdist} command has a \longprogramopt{formats} option,
-similar to the \command{sdist} command, which you can use to select the
-types of built distribution to generate: for example,
-
-\begin{verbatim}
-python setup.py bdist --format=zip
-\end{verbatim}
-
-would, when run on a \UNIX{} system, create
-\file{Distutils-1.0.\filevar{plat}.zip}---again, this archive would be
-unpacked from the root directory to install the Distutils.
-
-The available formats for built distributions are:
-\begin{tableiii}{l|l|c}{code}%
- {Format}{Description}{Notes}
- \lineiii{gztar}{gzipped tar file (\file{.tar.gz})}{(1),(3)}
- \lineiii{ztar}{compressed tar file (\file{.tar.Z})}{(3)}
- \lineiii{tar}{tar file (\file{.tar})}{(3)}
- \lineiii{zip}{zip file (\file{.zip})}{(4)}
- \lineiii{rpm}{RPM}{(5)}
- \lineiii{pkgtool}{Solaris \program{pkgtool}}{}
- \lineiii{sdux}{HP-UX \program{swinstall}}{}
- \lineiii{rpm}{RPM}{(5)}
-% \lineiii{srpm}{source RPM}{(5) \XXX{to do!}}
- \lineiii{wininst}{self-extracting ZIP file for Windows}{(2),(4)}
-\end{tableiii}
-
-\noindent Notes:
-\begin{description}
-\item[(1)] default on \UNIX
-\item[(2)] default on Windows \XXX{to-do!}
-\item[(3)] requires external utilities: \program{tar} and possibly one
- of \program{gzip}, \program{bzip2}, or \program{compress}
-\item[(4)] requires either external \program{zip} utility or
- \module{zipfile} module (part of the standard Python library since
- Python~1.6)
-\item[(5)] requires external \program{rpm} utility, version 3.0.4 or
- better (use \code{rpm --version} to find out which version you have)
-\end{description}
-
-You don't have to use the \command{bdist} command with the
-\longprogramopt{formats} option; you can also use the command that
-directly implements the format you're interested in. Some of these
-\command{bdist} ``sub-commands'' actually generate several similar
-formats; for instance, the \command{bdist\_dumb} command generates all
-the ``dumb'' archive formats (\code{tar}, \code{ztar}, \code{gztar}, and
-\code{zip}), and \command{bdist\_rpm} generates both binary and source
-RPMs. The \command{bdist} sub-commands, and the formats generated by
-each, are:
-\begin{tableii}{l|l}{command}%
- {Command}{Formats}
- \lineii{bdist\_dumb}{tar, ztar, gztar, zip}
- \lineii{bdist\_rpm}{rpm, srpm}
- \lineii{bdist\_wininst}{wininst}
-\end{tableii}
-
-The following sections give details on the individual \command{bdist\_*}
-commands.
-
-
-\subsection{Creating dumb built distributions}
-\label{creating-dumb}
-
-\XXX{Need to document absolute vs. prefix-relative packages here, but
- first I have to implement it!}
-
-
-\subsection{Creating RPM packages}
-\label{creating-rpms}
-
-The RPM format is used by many popular Linux distributions, including
-Red Hat, SuSE, and Mandrake. If one of these (or any of the other
-RPM-based Linux distributions) is your usual environment, creating RPM
-packages for other users of that same distribution is trivial.
-Depending on the complexity of your module distribution and differences
-between Linux distributions, you may also be able to create RPMs that
-work on different RPM-based distributions.
-
-The usual way to create an RPM of your module distribution is to run the
-\command{bdist\_rpm} command:
-
-\begin{verbatim}
-python setup.py bdist_rpm
-\end{verbatim}
-
-or the \command{bdist} command with the \longprogramopt{format} option:
-
-\begin{verbatim}
-python setup.py bdist --formats=rpm
-\end{verbatim}
-
-The former allows you to specify RPM-specific options; the latter allows
-you to easily specify multiple formats in one run. If you need to do
-both, you can explicitly specify multiple \command{bdist\_*} commands
-and their options:
-
-\begin{verbatim}
-python setup.py bdist_rpm --packager="John Doe " \
- bdist_wininst --target_version="2.0"
-\end{verbatim}
-
-Creating RPM packages is driven by a \file{.spec} file, much as using
-the Distutils is driven by the setup script. To make your life easier,
-the \command{bdist\_rpm} command normally creates a \file{.spec} file
-based on the information you supply in the setup script, on the command
-line, and in any Distutils configuration files. Various options and
-sections in the \file{.spec} file are derived from options in the setup
-script as follows:
-\begin{tableii}{l|l}{textrm}%
- {RPM \file{.spec} file option or section}{Distutils setup script option}
- \lineii{Name}{\option{name}}
- \lineii{Summary (in preamble)}{\option{description}}
- \lineii{Version}{\option{version}}
- \lineii{Vendor}{\option{author} and \option{author\_email}, or \\&
- \option{maintainer} and \option{maintainer\_email}}
- \lineii{Copyright}{\option{licence}}
- \lineii{Url}{\option{url}}
- \lineii{\%description (section)}{\option{long\_description}}
-\end{tableii}
-
-Additionally, there many options in \file{.spec} files that don't have
-corresponding options in the setup script. Most of these are handled
-through options to the \command{bdist\_rpm} command as follows:
-\begin{tableiii}{l|l|l}{textrm}%
- {RPM \file{.spec} file option or section}%
- {\command{bdist\_rpm} option}%
- {default value}
- \lineiii{Release}{\option{release}}{``1''}
- \lineiii{Group}{\option{group}}{``Development/Libraries''}
- \lineiii{Vendor}{\option{vendor}}{(see above)}
- \lineiii{Packager}{\option{packager}}{(none)}
- \lineiii{Provides}{\option{provides}}{(none)}
- \lineiii{Requires}{\option{requires}}{(none)}
- \lineiii{Conflicts}{\option{conflicts}}{(none)}
- \lineiii{Obsoletes}{\option{obsoletes}}{(none)}
- \lineiii{Distribution}{\option{distribution\_name}}{(none)}
- \lineiii{BuildRequires}{\option{build\_requires}}{(none)}
- \lineiii{Icon}{\option{icon}}{(none)}
-\end{tableiii}
-Obviously, supplying even a few of these options on the command-line
-would be tedious and error-prone, so it's usually best to put them in
-the setup configuration file, \file{setup.cfg}---see
-section~\ref{setup-config}. If you distribute or package many Python
-module distributions, you might want to put options that apply to all of
-them in your personal Distutils configuration file
-(\file{\textasciitilde/.pydistutils.cfg}).
-
-There are three steps to building a binary RPM package, all of which are
-handled automatically by the Distutils:
-\begin{enumerate}
-\item create a \file{.spec} file, which describes the package (analogous
- to the Distutils setup script; in fact, much of the information in the
- setup script winds up in the \file{.spec} file)
-\item create the source RPM
-\item create the ``binary'' RPM (which may or may not contain binary
- code, depending on whether your module distribution contains Python
- extensions)
-\end{enumerate}
-Normally, RPM bundles the last two steps together; when you use the
-Distutils, all three steps are typically bundled together.
-
-If you wish, you can separate these three steps. You can use the
-\longprogramopt{spec-only} option to make \command{bdist\_rpm} just
-create the \file{.spec} file and exit; in this case, the \file{.spec}
-file will be written to the ``distribution directory''---normally
-\file{dist/}, but customizable with the \longprogramopt{dist-dir}
-option. (Normally, the \file{.spec} file winds up deep in the ``build
-tree,'' in a temporary directory created by \command{bdist\_rpm}.)
-
-\XXX{this isn't implemented yet---is it needed?!}
-You can also specify a custom \file{.spec} file with the
-\longprogramopt{spec-file} option; used in conjunction with
-\longprogramopt{spec-only}, this gives you an opportunity to customize
-the \file{.spec} file manually:
-
-\begin{verbatim}
-> python setup.py bdist_rpm --spec-only
-# ...edit dist/FooBar-1.0.spec
-> python setup.py bdist_rpm --spec-file=dist/FooBar-1.0.spec
-\end{verbatim}
-
-(Although a better way to do this is probably to override the standard
-\command{bdist\_rpm} command with one that writes whatever else you want
-to the \file{.spec} file.)
-
-
-\subsection{Creating Windows Installers}
-\label{creating-wininst}
-
-Executable installers are the natural format for binary distributions
-on Windows. They display a nice graphical user interface, display
-some information about the module distribution to be installed taken
-from the metadata in the setup script, let the user select a few
-options, and start or cancel the installation.
-
-Since the metadata is taken from the setup script, creating Windows
-installers is usually as easy as running:
-
-\begin{verbatim}
-python setup.py bdist_wininst
-\end{verbatim}
-
-or the \command{bdist} command with the \longprogramopt{formats} option:
-
-\begin{verbatim}
-python setup.py bdist --formats=wininst
-\end{verbatim}
-
-If you have a pure module distribution (only containing pure Python
-modules and packages), the resulting installer will be version
-independent and have a name like \file{foo-1.0.win32.exe}. These
-installers can even be created on \UNIX{} or MacOS platforms.
-
-If you have a non-pure distribution, the extensions can only be
-created on a Windows platform, and will be Python version dependent.
-The installer filename will reflect this and now has the form
-\file{foo-1.0.win32-py2.0.exe}. You have to create a separate installer
-for every Python version you want to support.
-
-The installer will try to compile pure modules into bytecode after
-installation on the target system in normal and optimizing mode. If
-you don't want this to happen for some reason, you can run the
-\command{bdist_wininst} command with the
-\longprogramopt{no-target-compile} and/or the
-\longprogramopt{no-target-optimize} option.
-
-By default the installer will display the cool ``Python Powered'' logo
-when it is run, but you can also supply your own bitmap which must be
-a Windows \file{.bmp} file with the \longprogramopt{bitmap} option.
-
-The installer will also display a large title on the desktop
-background window when it is run, which is constructed from the name
-of your distribution and the version number. This can be changed to
-another text by using the \longprogramopt{title} option.
-
-The installer file will be written to the ``distribution directory''
---- normally \file{dist/}, but customizable with the
-\longprogramopt{dist-dir} option.
-
-\subsubsection{The Postinstallation script}
-\label{postinstallation-script}
-
-Starting with Python 2.3, a postinstallation script can be specified
-which the \longprogramopt{install-script} option. The basename of the
-script must be specified, and the script filename must also be listed
-in the scripts argument to the setup function.
-
-This script will be run at installation time on the target system
-after all the files have been copied, with argv[1] set to '-install',
-and again at uninstallation time before the files are removed with argv[1]
-set to '-remove'.
-
-The installation script runs embedded in the windows installer, every
-output (sys.stdout, sys.stderr) is redirected into a buffer and will
-be displayed in the GUI after the script has finished.
-
-Some functions especially useful in this context are available in the
-installation script.
-
-\begin{verbatim}
-dir_created(pathname)
-file_created(pathname)
-\end{verbatim}
-
-These functions should be called when a directory or file is created
-by the postinstall script at installation time. It will register the
-pathname with the uninstaller, so that it will be removed when the
-distribution is uninstalled. To be safe, directories are only removed
-if they are empty.
-
-\begin{verbatim}
-get_special_folder_path(csidl_string)
-\end{verbatim}
-
-This function can be used to retrieve special folder locations on
-Windows like the Start Menu or the Desktop. It returns the full path
-to the folder. 'csidl_string' must be on of the following strings:
-
-\begin{verbatim}
-"CSIDL_APPDATA"
-
-"CSIDL_COMMON_STARTMENU"
-"CSIDL_STARTMENU"
-
-"CSIDL_COMMON_DESKTOPDIRECTORY"
-"CSIDL_DESKTOPDIRECTORY"
-
-"CSIDL_COMMON_STARTUP"
-"CSIDL_STARTUP"
-
-"CSIDL_COMMON_PROGRAMS"
-"CSIDL_PROGRAMS"
-
-"CSIDL_FONTS"
-\end{verbatim}
-
-If the folder cannot be retrieved, OSError is raised.
-
-Which folders are available depends on the exact Windows version, and probably
-also the configuration. For details refer to Microsoft's documentation of the
-\code{SHGetSpecialFolderPath} function.
-
-\begin{verbatim}
-create_shortcut(target, description, filename[, arguments[,
- workdir[, iconpath[, iconindex]]]])
-\end{verbatim}
-
-This function creates a shortcut.
-\var{target} is the path to the program to be started by the shortcut.
-\var{description} is the description of the sortcut.
-\var{filename} is the title of the shortcut that the user will see.
-\var{arguments} specifies the command line arguments, if any.
-\var{workdir} is the working directory for the program.
-\var{iconpath} is the file containing the icon for the shortcut,
-and \var{iconindex} is the index of the icon in the file
-\var{iconpath}. Again, for details consult the Microsoft
-documentation for the \code{IShellLink} interface.
-
-\section{Registering with the Package Index}
-\label{package-index}
-
-The Python Package Index (PyPI) holds meta-data describing distributions
-packaged with distutils. The distutils command \command{register} is
-used to submit your distribution's meta-data to the index. It is invoked
-as follows:
-
-\begin{verbatim}
-python setup.py register
-\end{verbatim}
-
-Distutils will respond with the following prompt:
-
-\begin{verbatim}
-running register
-We need to know who you are, so please choose either:
- 1. use your existing login,
- 2. register as a new user,
- 3. have the server generate a new password for you (and email it to you), or
- 4. quit
-Your selection [default 1]:
-\end{verbatim}
-
-\noindent Note: if your username and password are saved locally, you will
-not see this menu.
-
-If you have not registered with PyPI, then you will need to do so now. You
-should choose option 2, and enter your details as required. Soon after
-submitting your details, you will receive an email which will be used to
-confirm your registration.
-
-Once you are registered, you may choose option 1 from the menu. You will
-be prompted for your PyPI username and password, and \command{register}
-will then submit your meta-data to the index.
-
-You may submit any number of versions of your distribution to the index. If
-you alter the meta-data for a particular version, you may submit it again
-and the index will be updated.
-
-PyPI holds a record for each (name, version) combination submitted. The
-first user to submit information for a given name is designated the Owner
-of that name. They may submit changes through the \command{register}
-command or through the web interface. They may also designate other users
-as Owners or Maintainers. Maintainers may edit the package information, but
-not designate other Owners or Maintainers.
-
-By default PyPI will list all versions of a given package. To hide certain
-versions, the Hidden property should be set to yes. This must be edited
-through the web interface.
-
-
-
-\section{Examples}
-\label{examples}
-
-\subsection{Pure Python distribution (by module)}
-\label{pure-mod}
-
-If you're just distributing a couple of modules, especially if they
-don't live in a particular package, you can specify them individually
-using the \option{py\_modules} option in the setup script.
-
-In the simplest case, you'll have two files to worry about: a setup
-script and the single module you're distributing, \file{foo.py} in this
-example:
-\begin{verbatim}
-/
- setup.py
- foo.py
-\end{verbatim}
-(In all diagrams in this section, \verb|| will refer to the
-distribution root directory.) A minimal setup script to describe this
-situation would be:
-\begin{verbatim}
-from distutils.core import setup
-setup(name = "foo", version = "1.0",
- py_modules = ["foo"])
-\end{verbatim}
-Note that the name of the distribution is specified independently with
-the \option{name} option, and there's no rule that says it has to be the
-same as the name of the sole module in the distribution (although that's
-probably a good convention to follow). However, the distribution name
-is used to generate filenames, so you should stick to letters, digits,
-underscores, and hyphens.
-
-Since \option{py\_modules} is a list, you can of course specify multiple
-modules, eg. if you're distributing modules \module{foo} and
-\module{bar}, your setup might look like this:
-\begin{verbatim}
-/
- setup.py
- foo.py
- bar.py
-\end{verbatim}
-and the setup script might be
-\begin{verbatim}
-from distutils.core import setup
-setup(name = "foobar", version = "1.0",
- py_modules = ["foo", "bar"])
-\end{verbatim}
-
-You can put module source files into another directory, but if you have
-enough modules to do that, it's probably easier to specify modules by
-package rather than listing them individually.
-
-
-\subsection{Pure Python distribution (by package)}
-\label{pure-pkg}
-
-If you have more than a couple of modules to distribute, especially if
-they are in multiple packages, it's probably easier to specify whole
-packages rather than individual modules. This works even if your
-modules are not in a package; you can just tell the Distutils to process
-modules from the root package, and that works the same as any other
-package (except that you don't have to have an \file{\_\_init\_\_.py}
-file).
-
-The setup script from the last example could also be written as
-\begin{verbatim}
-from distutils.core import setup
-setup(name = "foobar", version = "1.0",
- packages = [""])
-\end{verbatim}
-(The empty string stands for the root package.)
-
-If those two files are moved into a subdirectory, but remain in the root
-package, e.g.:
-\begin{verbatim}
-/
- setup.py
- src/ foo.py
- bar.py
-\end{verbatim}
-then you would still specify the root package, but you have to tell the
-Distutils where source files in the root package live:
-\begin{verbatim}
-from distutils.core import setup
-setup(name = "foobar", version = "1.0",
- package_dir = {"": "src"},
- packages = [""])
-\end{verbatim}
-
-More typically, though, you will want to distribute multiple modules in
-the same package (or in sub-packages). For example, if the \module{foo}
-and \module{bar} modules belong in package \module{foobar}, one way to
-layout your source tree is
-\begin{verbatim}
-/
- setup.py
- foobar/
- __init__.py
- foo.py
- bar.py
-\end{verbatim}
-This is in fact the default layout expected by the Distutils, and the
-one that requires the least work to describe in your setup script:
-\begin{verbatim}
-from distutils.core import setup
-setup(name = "foobar", version = "1.0",
- packages = ["foobar"])
-\end{verbatim}
-
-If you want to put modules in directories not named for their package,
-then you need to use the \option{package\_dir} option again. For
-example, if the \file{src} directory holds modules in the
-\module{foobar} package:
-\begin{verbatim}
-/
- setup.py
- src/
- __init__.py
- foo.py
- bar.py
-\end{verbatim}
-an appropriate setup script would be
-\begin{verbatim}
-from distutils.core import setup
-setup(name = "foobar", version = "1.0",
- package_dir = {"foobar" : "src"},
- packages = ["foobar"])
-\end{verbatim}
-
-Or, you might put modules from your main package right in the
-distribution root:
-\begin{verbatim}
-/
- setup.py
- __init__.py
- foo.py
- bar.py
-\end{verbatim}
-in which case your setup script would be
-\begin{verbatim}
-from distutils.core import setup
-setup(name = "foobar", version = "1.0",
- package_dir = {"foobar" : ""},
- packages = ["foobar"])
-\end{verbatim}
-(The empty string also stands for the current directory.)
-
-If you have sub-packages, they must be explicitly listed in
-\option{packages}, but any entries in \option{package\_dir}
-automatically extend to sub-packages. (In other words, the Distutils
-does \emph{not} scan your source tree, trying to figure out which
-directories correspond to Python packages by looking for
-\file{\_\_init\_\_.py} files.) Thus, if the default layout grows a
-sub-package:
-\begin{verbatim}
-/
- setup.py
- foobar/
- __init__.py
- foo.py
- bar.py
- subfoo/
- __init__.py
- blah.py
-\end{verbatim}
-then the corresponding setup script would be
-\begin{verbatim}
-from distutils.core import setup
-setup(name = "foobar", version = "1.0",
- packages = ["foobar", "foobar.subfoo"])
-\end{verbatim}
-(Again, the empty string in \option{package\_dir} stands for the current
-directory.)
-
-
-\subsection{Single extension module}
-\label{single-ext}
-
-Extension modules are specified using the \option{ext\_modules} option.
-\option{package\_dir} has no effect on where extension source files are
-found; it only affects the source for pure Python modules. The simplest
-case, a single extension module in a single C source file, is:
-\begin{verbatim}
-/
- setup.py
- foo.c
-\end{verbatim}
-If the \module{foo} extension belongs in the root package, the setup
-script for this could be
-\begin{verbatim}
-from distutils.core import setup
-setup(name = "foobar", version = "1.0",
- ext_modules = [Extension("foo", ["foo.c"])])
-\end{verbatim}
-
-If the extension actually belongs in a package, say \module{foopkg},
-then
-
-With exactly the same source tree layout, this extension can be put in
-the \module{foopkg} package simply by changing the name of the
-extension:
-\begin{verbatim}
-from distutils.core import setup
-setup(name = "foobar", version = "1.0",
- ext_modules = [Extension("foopkg.foo", ["foo.c"])])
-\end{verbatim}
-
-
-%\subsection{Multiple extension modules}
-%\label{multiple-ext}
-
-
-%\subsection{Putting it all together}
-
-
-%\section{Extending the Distutils}
-%\label{extending}
-
-
-%\subsection{Extending existing commands}
-%\label{extend-existing}
-
-
-%\subsection{Writing new commands}
-%\label{new-commands}
-
-%\XXX{Would an uninstall command be a good example here?}
-
-
-
-\section{Reference}
-\label{reference}
-
-
-%\subsection{Building modules: the \protect\command{build} command family}
-%\label{build-cmds}
-
-%\subsubsection{\protect\command{build}}
-%\label{build-cmd}
-
-%\subsubsection{\protect\command{build\_py}}
-%\label{build-py-cmd}
-
-%\subsubsection{\protect\command{build\_ext}}
-%\label{build-ext-cmd}
-
-%\subsubsection{\protect\command{build\_clib}}
-%\label{build-clib-cmd}
-
-
-\subsection{Installing modules: the \protect\command{install} command family}
-\label{install-cmd}
-
-The install command ensures that the build commands have been run and then
-runs the subcommands \command{install\_lib},
-\command{install\_data} and
-\command{install\_scripts}.
-
-%\subsubsection{\protect\command{install\_lib}}
-%\label{install-lib-cmd}
-
-\subsubsection{\protect\command{install\_data}}
-\label{install-data-cmd}
-This command installs all data files provided with the distribution.
-
-\subsubsection{\protect\command{install\_scripts}}
-\label{install-scripts-cmd}
-This command installs all (Python) scripts in the distribution.
-
-
-%\subsection{Cleaning up: the \protect\command{clean} command}
-%\label{clean-cmd}
-
-
-\subsection{Creating a source distribution: the
- \protect\command{sdist} command}
-\label{sdist-cmd}
-
-
-\XXX{fragment moved down from above: needs context!}
-
-The manifest template commands are:
-\begin{tableii}{ll}{command}{Command}{Description}
- \lineii{include \var{pat1} \var{pat2} ... }
- {include all files matching any of the listed patterns}
- \lineii{exclude \var{pat1} \var{pat2} ... }
- {exclude all files matching any of the listed patterns}
- \lineii{recursive-include \var{dir} \var{pat1} \var{pat2} ... }
- {include all files under \var{dir} matching any of the listed patterns}
- \lineii{recursive-exclude \var{dir} \var{pat1} \var{pat2} ...}
- {exclude all files under \var{dir} matching any of the listed patterns}
- \lineii{global-include \var{pat1} \var{pat2} ...}
- {include all files anywhere in the source tree matching\\&
- any of the listed patterns}
- \lineii{global-exclude \var{pat1} \var{pat2} ...}
- {exclude all files anywhere in the source tree matching\\&
- any of the listed patterns}
- \lineii{prune \var{dir}}{exclude all files under \var{dir}}
- \lineii{graft \var{dir}}{include all files under \var{dir}}
-\end{tableii}
-The patterns here are \UNIX-style ``glob'' patterns: \code{*} matches any
-sequence of regular filename characters, \code{?} matches any single
-regular filename character, and \code{[\var{range}]} matches any of the
-characters in \var{range} (e.g., \code{a-z}, \code{a-zA-Z},
-\code{a-f0-9\_.}). The definition of ``regular filename character'' is
-platform-specific: on \UNIX{} it is anything except slash; on Windows
-anything except backslash or colon; on MacOS anything except colon.
-
-\XXX{Windows and MacOS support not there yet}
-
-
-%\subsection{Creating a built distribution: the
-% \protect\command{bdist} command family}
-%\label{bdist-cmds}
-
-
-%\subsubsection{\protect\command{bdist}}
-
-%\subsubsection{\protect\command{bdist\_dumb}}
-
-%\subsubsection{\protect\command{bdist\_rpm}}
-
-%\subsubsection{\protect\command{bdist\_wininst}}
-
-
-\input{sysconfig}
-
-
-\end{document}
diff --git a/Doc/dist/sysconfig.tex b/Doc/dist/sysconfig.tex
deleted file mode 100644
index c3e135d9d8..0000000000
--- a/Doc/dist/sysconfig.tex
+++ /dev/null
@@ -1,113 +0,0 @@
-\section{\module{distutils.sysconfig} ---
- System configuration information}
-
-\declaremodule{standard}{distutils.sysconfig}
-\modulesynopsis{Low-level access to configuration information of the
- Python interpreter.}
-\moduleauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
-\moduleauthor{Greg Ward}{gward@python.net}
-\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
-
-
-The \module{distutils.sysconfig} module provides access to Python's
-low-level configuration information. The specific configuration
-variables available depend heavily on the platform and configuration.
-The specific variables depend on the build process for the specific
-version of Python being run; the variables are those found in the
-\file{Makefile} and configuration header that are installed with
-Python on \UNIX{} systems. The configuration header is called
-\file{pyconfig.h} for Python versions starting with 2.2, and
-\file{config.h} for earlier versions of Python.
-
-Some additional functions are provided which perform some useful
-manipulations for other parts of the \module{distutils} package.
-
-
-\begin{datadesc}{PREFIX}
- The result of \code{os.path.normpath(sys.prefex)}.
-\end{datadesc}
-
-\begin{datadesc}{EXEC_PREFIX}
- The result of \code{os.path.normpath(sys.exec_prefex)}.
-\end{datadesc}
-
-\begin{funcdesc}{get_config_var}{name}
- Return the value of a single variable. This is equivalent to
- \code{get_config_vars().get(\var{name})}.
-\end{funcdesc}
-
-\begin{funcdesc}{get_config_vars}{\moreargs}
- Return a set of variable definitions. If there are no arguments,
- this returns a dictionary mapping names of configuration variables
- to values. If arguments are provided, they should be strings, and
- the return value will be a sequence giving the associated values.
- If a given name does not have a corresponding value, \code{None}
- will be included for that variable.
-\end{funcdesc}
-
-\begin{funcdesc}{get_config_h_filename}{}
- Return the full path name of the configuration header. For \UNIX,
- this will be the header generated by the \program{configure} script;
- for other platforms the header will have been supplied directly by
- the Python source distribution. The file is a platform-specific
- text file.
-\end{funcdesc}
-
-\begin{funcdesc}{get_makefile_filename}{}
- Return the full path name of the \file{Makefile} used to build
- Python. For \UNIX, this will be a file generated by the
- \program{configure} script; the meaning for other platforms will
- vary. The file is a platform-specific text file, if it exists.
- This function is only useful on \POSIX{} platforms.
-\end{funcdesc}
-
-\begin{funcdesc}{get_python_inc}{\optional{plat_specific\optional{, prefix}}}
- Return the directory for either the general or platform-dependent C
- include files. If \var{plat_specific} is true, the
- platform-dependent include directory is returned; if false or
- omitted, the platform-independent directory is returned. If
- \var{prefix} is given, it is used as either the prefix instead of
- \constant{PREFIX}, or as the exec-prefix instead of
- \constant{EXEC_PREFIX} if \var{plat_specific} is true.
-\end{funcdesc}
-
-\begin{funcdesc}{get_python_lib}{\optional{plat_specific\optional{,
- standard_lib\optional{, prefix}}}}
- Return the directory for either the general or platform-dependent
- library installation. If \var{plat_specific} is true, the
- platform-dependent include directory is returned; if false or
- omitted, the platform-independent directory is returned. If
- \var{prefix} is given, it is used as either the prefix instead of
- \constant{PREFIX}, or as the exec-prefix instead of
- \constant{EXEC_PREFIX} if \var{plat_specific} is true. If
- \var{standard_lib} is true, the directory for the standard library
- is returned rather than the directory for the installation of
- third-party extensions.
-\end{funcdesc}
-
-
-The following function is only intended for use within the
-\module{distutils} package.
-
-\begin{funcdesc}{customize_compiler}{compiler}
- Do any platform-specific customization of a
- \class{distutils.ccompiler.CCompiler} instance.
-
- This function is only needed on \UNIX{} at this time, but should be
- called consistently to support forward-compatibility. It inserts
- the information that varies across \UNIX{} flavors and is stored in
- Python's \file{Makefile}. This information includes the selected
- compiler, compiler and linker options, and the extension used by the
- linker for shared objects.
-\end{funcdesc}
-
-
-This function is even more special-purpose, and should only be used
-from Python's own build procedures.
-
-\begin{funcdesc}{set_python_build}{}
- Inform the \module{distutils.sysconfig} module that it is being used
- as part of the build process for Python. This changes a lot of
- relative locations for files, allowing them to be located in the
- build area rather than in an installed Python.
-\end{funcdesc}
diff --git a/Doc/doc/doc.tex b/Doc/doc/doc.tex
deleted file mode 100644
index 11385543ea..0000000000
--- a/Doc/doc/doc.tex
+++ /dev/null
@@ -1,1922 +0,0 @@
-\documentclass{howto}
-\usepackage{ltxmarkup}
-
-\title{Documenting Python}
-
-\makeindex
-
-\input{boilerplate}
-
-% Now override the stuff that includes author information;
-% Guido did *not* write this one!
-
-\author{Fred L. Drake, Jr.}
-\authoraddress{
- PythonLabs \\
- Email: \email{fdrake@acm.org}
-}
-
-
-\begin{document}
-
-\maketitle
-
-\begin{abstract}
-\noindent
-The Python language has a substantial body of
-documentation, much of it contributed by various authors. The markup
-used for the Python documentation is based on \LaTeX{} and requires a
-significant set of macros written specifically for documenting Python.
-This document describes the macros introduced to support Python
-documentation and how they should be used to support a wide range of
-output formats.
-
-This document describes the document classes and special markup used
-in the Python documentation. Authors may use this guide, in
-conjunction with the template files provided with the
-distribution, to create or maintain whole documents or sections.
-\end{abstract}
-
-\tableofcontents
-
-
-\section{Introduction \label{intro}}
-
- Python's documentation has long been considered to be good for a
- free programming language. There are a number of reasons for this,
- the most important being the early commitment of Python's creator,
- Guido van Rossum, to providing documentation on the language and its
- libraries, and the continuing involvement of the user community in
- providing assistance for creating and maintaining documentation.
-
- The involvement of the community takes many forms, from authoring to
- bug reports to just plain complaining when the documentation could
- be more complete or easier to use. All of these forms of input from
- the community have proved useful during the time I've been involved
- in maintaining the documentation.
-
- This document is aimed at authors and potential authors of
- documentation for Python. More specifically, it is for people
- contributing to the standard documentation and developing additional
- documents using the same tools as the standard documents. This
- guide will be less useful for authors using the Python documentation
- tools for topics other than Python, and less useful still for
- authors not using the tools at all.
-
- The material in this guide is intended to assist authors using the
- Python documentation tools. It includes information on the source
- distribution of the standard documentation, a discussion of the
- document types, reference material on the markup defined in the
- document classes, a list of the external tools needed for processing
- documents, and reference material on the tools provided with the
- documentation resources. At the end, there is also a section
- discussing future directions for the Python documentation and where
- to turn for more information.
-
-\section{Directory Structure \label{directories}}
-
- The source distribution for the standard Python documentation
- contains a large number of directories. While third-party documents
- do not need to be placed into this structure or need to be placed
- within a similar structure, it can be helpful to know where to look
- for examples and tools when developing new documents using the
- Python documentation tools. This section describes this directory
- structure.
-
- The documentation sources are usually placed within the Python
- source distribution as the top-level directory \file{Doc/}, but
- are not dependent on the Python source distribution in any way.
-
- The \file{Doc/} directory contains a few files and several
- subdirectories. The files are mostly self-explanatory, including a
- \file{README} and a \file{Makefile}. The directories fall into
- three categories:
-
- \begin{definitions}
- \term{Document Sources}
- The \LaTeX{} sources for each document are placed in a
- separate directory. These directories are given short
- names which vaguely indicate the document in each:
-
- \begin{tableii}{p{.75in}|p{3in}}{filenq}{Directory}{Document Title}
- \lineii{api/}
- {\citetitle[../api/api.html]{The Python/C API}}
- \lineii{dist/}
- {\citetitle[../dist/dist.html]{Distributing Python Modules}}
- \lineii{doc/}
- {\citetitle[../doc/doc.html]{Documenting Python}}
- \lineii{ext/}
- {\citetitle[../ext/ext.html]{Extending and Embedding the Python Interpreter}}
- \lineii{inst/}
- {\citetitle[../inst/inst.html]{Installing Python Modules}}
- \lineii{lib/}
- {\citetitle[../lib/lib.html]{Python Library Reference}}
- \lineii{mac/}
- {\citetitle[../mac/mac.html]{Macintosh Module Reference}}
- \lineii{ref/}
- {\citetitle[../ref/ref.html]{Python Reference Manual}}
- \lineii{tut/}
- {\citetitle[../tut/tut.html]{Python Tutorial}}
- \end{tableii}
-
- \term{Format-Specific Output}
- Most output formats have a directory which contains a
- \file{Makefile} which controls the generation of that format
- and provides storage for the formatted documents. The only
- variations within this category are the Portable Document
- Format (PDF) and PostScript versions are placed in the
- directories \file{paper-a4/} and \file{paper-letter/} (this
- causes all the temporary files created by \LaTeX{} to be kept
- in the same place for each paper size, where they can be more
- easily ignored).
-
- \begin{tableii}{p{.75in}|p{3in}}{filenq}{Directory}{Output Formats}
- \lineii{html/}{HTML output}
- \lineii{info/}{GNU info output}
- \lineii{isilo/}{\ulink{iSilo}{http://www.isilo.com/}
- documents (for Palm OS devices)}
- \lineii{paper-a4/}{PDF and PostScript, A4 paper}
- \lineii{paper-letter/}{PDF and PostScript, US-Letter paper}
- \end{tableii}
-
- \term{Supplemental Files}
- Some additional directories are used to store supplemental
- files used for the various processes. Directories are
- included for the shared \LaTeX{} document classes, the
- \LaTeX2HTML support, template files for various document
- components, and the scripts used to perform various steps in
- the formatting processes.
-
- \begin{tableii}{p{.75in}|p{3in}}{filenq}{Directory}{Contents}
- \lineii{perl/}{Support for \LaTeX2HTML processing}
- \lineii{templates/}{Example files for source documents}
- \lineii{texinputs/}{Style implementation for \LaTeX}
- \lineii{tools/}{Custom processing scripts}
- \end{tableii}
-
- \end{definitions}
-
-
-\section{Style Guide \label{style-guide}}
-
- The Python documentation should follow the \citetitle
- [http://developer.apple.com/techpubs/macos8/pdf/apple_styleguide00.pdf]
- {Apple Publications Style Guide} wherever possible. This particular
- style guide was selected mostly because it seems reasonable and is
- easy to get online. (Printed copies are available; see the Apple's
- \citetitle[http://developer.apple.com/techpubs/faq.html]{Developer
- Documentation FAQ} for more information.)
-
- Topics which are not covered in the Apple's style guide will be
- discussed in this document if necessary.
-
- Many special names are used in the Python documentation, including
- the names of operating systems, programming languages, standards
- bodies, and the like. Many of these were assigned \LaTeX{} macros
- at some point in the distant past, and these macros lived on long
- past their usefulness. In the current markup, most of these entities
- are not assigned any special markup, but the preferred spellings are
- given here to aid authors in maintaining the consistency of
- presentation in the Python documentation.
-
- Other terms and words deserve special mention as well; these conventions
- should be used to ensure consistency throughout the documentation:
-
- \begin{description}
- \item[CPU]
- For ``central processing unit.'' Many style guides say this
- should be spelled out on the first use (and if you must use it,
- do so!). For the Python documentation, this abbreviation should
- be avoided since there's no reasonable way to predict which occurance
- will be the first seen by the reader. It is better to use the
- word ``processor'' instead.
-
- \item[\POSIX]
- The name assigned to a particular group of standards. This is
- always uppercase. Use the macro \macro{POSIX} to represent this
- name.
-
- \item[Python]
- The name of our favorite programming language is always
- capitalized.
-
- \item[Unicode]
- The name of a character set and matching encoding. This is
- always written capitalized.
-
- \item[\UNIX]
- The name of the operating system developed at AT\&T Bell Labs
- in the early 1970s. Use the macro \macro{UNIX} to use this name.
- \end{description}
-
-
-\section{\LaTeX{} Primer \label{latex-primer}}
-
- This section is a brief introduction to \LaTeX{} concepts and
- syntax, to provide authors enough information to author documents
- productively without having to become ``\TeX{}nicians.''
-
- Perhaps the most important concept to keep in mind while marking up
- Python documentation is that while \TeX{} is unstructured, \LaTeX{} was
- designed as a layer on top of \TeX{} which specifically supports
- structured markup. The Python-specific markup is intended to extend
- the structure provided by standard \LaTeX{} document classes to
- support additional information specific to Python.
-
- \LaTeX{} documents contain two parts: the preamble and the body.
- The preamble is used to specify certain metadata about the document
- itself, such as the title, the list of authors, the date, and the
- \emph{class} the document belongs to. Additional information used
- to control index generation and the use of bibliographic databases
- can also be placed in the preamble. For most authors, the preamble
- can be most easily created by copying it from an existing document
- and modifying a few key pieces of information.
-
- The \dfn{class} of a document is used to place a document within a
- broad category of documents and set some fundamental formatting
- properties. For Python documentation, two classes are used: the
- \code{manual} class and the \code{howto} class. These classes also
- define the additional markup used to document Python concepts and
- structures. Specific information about these classes is provided in
- section \ref{classes}, ``Document Classes,'' below. The first thing
- in the preamble is the declaration of the document's class.
-
- After the class declaration, a number of \emph{macros} are used to
- provide further information about the document and setup any
- additional markup that is needed. No output is generated from the
- preamble; it is an error to include free text in the preamble
- because it would cause output.
-
- The document body follows the preamble. This contains all the
- printed components of the document marked up structurally. Generic
- \LaTeX{} structures include hierarchical sections, numbered and
- bulleted lists, and special structures for the document abstract and
- indexes.
-
- \subsection{Syntax \label{latex-syntax}}
-
- There are some things that an author of Python documentation needs
- to know about \LaTeX{} syntax.
-
- A \dfn{comment} is started by the ``percent'' character
- (\character{\%}) and continues through the end of the line and all
- leading whitespace on the following line. This is a little
- different from any programming language I know of, so an example
- is in order:
-
-\begin{verbatim}
-This is text.% comment
- This is more text. % another comment
-Still more text.
-\end{verbatim}
-
- The first non-comment character following the first comment is the
- letter \character{T} on the second line; the leading whitespace on
- that line is consumed as part of the first comment. This means
- that there is no space between the first and second sentences, so
- the period and letter \character{T} will be directly adjacent in
- the typeset document.
-
- Note also that though the first non-comment character after the
- second comment is the letter \character{S}, there is whitespace
- preceding the comment, so the two sentences are separated as
- expected.
-
- A \dfn{group} is an enclosure for a collection of text and
- commands which encloses the formatting context and constrains the
- scope of any changes to that context made by commands within the
- group. Groups can be nested hierarchically. The formatting
- context includes the font and the definition of additional macros
- (or overrides of macros defined in outer groups). Syntactically,
- groups are enclosed in braces:
-
-\begin{verbatim}
-{text in a group}
-\end{verbatim}
-
- An alternate syntax for a group using brackets, \code{[...]}, is
- used by macros and environment constructors which take optional
- parameters; brackets do not normally hold syntactic significance.
- A degenerate group, containing only one atomic bit of content,
- does not need to have an explicit group, unless it is required to
- avoid ambiguity. Since Python tends toward the explicit, groups
- are also made explicit in the documentation markup.
-
- Groups are used only sparingly in the Python documentation, except
- for their use in marking parameters to macros and environments.
-
- A \dfn{macro} is usually a simple construct which is identified by
- name and can take some number of parameters. In normal \LaTeX{}
- usage, one of these can be optional. The markup is introduced
- using the backslash character (\character{\e}), and the name is
- given by alphabetic characters (no digits, hyphens, or
- underscores). Required parameters should be marked as a group,
- and optional parameters should be marked using the alternate
- syntax for a group.
-
- For example, a macro named ``foo'' which takes a single parameter
- would appear like this:
-
-\begin{verbatim}
-\name{parameter}
-\end{verbatim}
-
- A macro which takes an optional parameter would be typed like this
- when the optional paramter is given:
-
-\begin{verbatim}
-\name[optional]
-\end{verbatim}
-
- If both optional and required parameters are to be required, it
- looks like this:
-
-\begin{verbatim}
-\name[optional]{required}
-\end{verbatim}
-
- A macro name may be followed by a space or newline; a space
- between the macro name and any parameters will be consumed, but
- this usage is not practiced in the Python documentation. Such a
- space is still consumed if there are no parameters to the macro,
- in which case inserting an empty group (\code{\{\}}) or explicit
- word space (\samp{\e\ }) immediately after the macro name helps to
- avoid running the expansion of the macro into the following text.
- Macros which take no parameters but which should not be followed
- by a word space do not need special treatment if the following
- character in the document source if not a name character (such as
- punctuation).
-
- Each line of this example shows an appropriate way to write text
- which includes a macro which takes no parameters:
-
-\begin{verbatim}
-This \UNIX{} is followed by a space.
-This \UNIX\ is also followed by a space.
-\UNIX, followed by a comma, needs no additional markup.
-\end{verbatim}
-
- An \dfn{environment} is a larger construct than a macro, and can
- be used for things with more content than would conveniently fit
- in a macro parameter. They are primarily used when formatting
- parameters need to be changed before and after a large chunk of
- content, but the content itself needs to be highly flexible. Code
- samples are presented using an environment, and descriptions of
- functions, methods, and classes are also marked using environments.
-
- Since the content of an environment is free-form and can consist
- of several paragraphs, they are actually marked using a pair of
- macros: \macro{begin} and \macro{end}. These macros both take the
- name of the environment as a parameter. An example is the
- environment used to mark the abstract of a document:
-
-\begin{verbatim}
-\begin{abstract}
- This is the text of the abstract. It concisely explains what
- information is found in the document.
-
- It can consist of multiple paragraphs.
-\end{abstract}
-\end{verbatim}
-
- An environment can also have required and optional parameters of
- its own. These follow the parameter of the \macro{begin} macro.
- This example shows an environment which takes a single required
- parameter:
-
-\begin{verbatim}
-\begin{datadesc}{controlnames}
- A 33-element string array that contains the \ASCII{} mnemonics for
- the thirty-two \ASCII{} control characters from 0 (NUL) to 0x1f
- (US), in order, plus the mnemonic \samp{SP} for the space character.
-\end{datadesc}
-\end{verbatim}
-
- There are a number of less-used marks in \LaTeX{} which are used
- to enter characters which are not found in \ASCII{} or which a
- considered special, or \emph{active} in \TeX{} or \LaTeX. Given
- that these are often used adjacent to other characters, the markup
- required to produce the proper character may need to be followed
- by a space or an empty group, or the markup can be enclosed in a
- group. Some which are found in Python documentation are:
-
-\begin{tableii}{c|l}{textrm}{Character}{Markup}
- \lineii{\textasciicircum}{\code{\e textasciicircum}}
- \lineii{\textasciitilde}{\code{\e textasciitilde}}
- \lineii{\textgreater}{\code{\e textgreater}}
- \lineii{\textless}{\code{\e textless}}
- \lineii{\c c}{\code{\e c c}}
- \lineii{\"o}{\code{\e"o}}
- \lineii{\o}{\code{\e o}}
-\end{tableii}
-
-
- \subsection{Hierarchical Structure \label{latex-structure}}
-
- \LaTeX{} expects documents to be arranged in a conventional,
- hierarchical way, with chapters, sections, sub-sections,
- appendixes, and the like. These are marked using macros rather
- than environments, probably because the end of a section can be
- safely inferred when a section of equal or higher level starts.
-
- There are six ``levels'' of sectioning in the document classes
- used for Python documentation, and the deepest two
- levels\footnote{The deepest levels have the highest numbers in the
- table.} are not used. The levels are:
-
- \begin{tableiii}{c|l|c}{textrm}{Level}{Macro Name}{Notes}
- \lineiii{1}{\macro{chapter}}{(1)}
- \lineiii{2}{\macro{section}}{}
- \lineiii{3}{\macro{subsection}}{}
- \lineiii{4}{\macro{subsubsection}}{}
- \lineiii{5}{\macro{paragraph}}{(2)}
- \lineiii{6}{\macro{subparagraph}}{}
- \end{tableiii}
-
- \noindent
- Notes:
-
- \begin{description}
- \item[(1)]
- Only used for the \code{manual} documents, as described in
- section \ref{classes}, ``Document Classes.''
- \item[(2)]
- Not the same as a paragraph of text; nobody seems to use this.
- \end{description}
-
-
-\section{Document Classes \label{classes}}
-
- Two \LaTeX{} document classes are defined specifically for use with
- the Python documentation. The \code{manual} class is for large
- documents which are sectioned into chapters, and the \code{howto}
- class is for smaller documents.
-
- The \code{manual} documents are larger and are used for most of the
- standard documents. This document class is based on the standard
- \LaTeX{} \code{report} class and is formatted very much like a long
- technical report. The \citetitle[../ref/ref.html]{Python Reference
- Manual} is a good example of a \code{manual} document, and the
- \citetitle[../lib/lib.html]{Python Library Reference} is a large
- example.
-
- The \code{howto} documents are shorter, and don't have the large
- structure of the \code{manual} documents. This class is based on
- the standard \LaTeX{} \code{article} class and is formatted somewhat
- like the Linux Documentation Project's ``HOWTO'' series as done
- originally using the LinuxDoc software. The original intent for the
- document class was that it serve a similar role as the LDP's HOWTO
- series, but the applicability of the class turns out to be somewhat
- broader. This class is used for ``how-to'' documents (this
- document is an example) and for shorter reference manuals for small,
- fairly cohesive module libraries. Examples of the later use include
-\citetitle[http://starship.python.net/crew/fdrake/manuals/krb5py/krb5py.html]{Using
- Kerberos from Python}, which contains reference material for an
- extension package. These documents are roughly equivalent to a
- single chapter from a larger work.
-
-
-\section{Special Markup Constructs \label{special-constructs}}
-
- The Python document classes define a lot of new environments and
- macros. This section contains the reference material for these
- facilities.
-
- \subsection{Markup for the Preamble \label{preamble-info}}
-
- \begin{macrodesc}{release}{\p{ver}}
- Set the version number for the software described in the
- document.
- \end{macrodesc}
-
- \begin{macrodesc}{setshortversion}{\p{sver}}
- Specify the ``short'' version number of the documented software
- to be \var{sver}.
- \end{macrodesc}
-
- \subsection{Meta-information Markup \label{meta-info}}
-
- \begin{macrodesc}{sectionauthor}{\p{author}\p{email}}
- Identifies the author of the current section. \var{author}
- should be the author's name such that it can be used for
- presentation (though it isn't), and \var{email} should be the
- author's email address. The domain name portion of
- the address should be lower case.
-
- No presentation is generated from this markup, but it is used to
- help keep track of contributions.
- \end{macrodesc}
-
- \subsection{Information Units \label{info-units}}
-
- XXX Explain terminology, or come up with something more ``lay.''
-
- There are a number of environments used to describe specific
- features provided by modules. Each environment requires
- parameters needed to provide basic information about what is being
- described, and the environment content should be the description.
- Most of these environments make entries in the general index (if
- one is being produced for the document); if no index entry is
- desired, non-indexing variants are available for many of these
- environments. The environments have names of the form
- \code{\var{feature}desc}, and the non-indexing variants are named
- \code{\var{feature}descni}. The available variants are explicitly
- included in the list below.
-
- For each of these environments, the first parameter, \var{name},
- provides the name by which the feature is accessed.
-
- Environments which describe features of objects within a module,
- such as object methods or data attributes, allow an optional
- \var{type name} parameter. When the feature is an attribute of
- class instances, \var{type name} only needs to be given if the
- class was not the most recently described class in the module; the
- \var{name} value from the most recent \env{classdesc} is implied.
- For features of built-in or extension types, the \var{type name}
- value should always be provided. Another special case includes
- methods and members of general ``protocols,'' such as the
- formatter and writer protocols described for the
- \module{formatter} module: these may be documented without any
- specific implementation classes, and will always require the
- \var{type name} parameter to be provided.
-
- \begin{envdesc}{cfuncdesc}{\p{type}\p{name}\p{args}}
- Environment used to described a C function. The \var{type}
- should be specified as a \keyword{typedef} name, \code{struct
- \var{tag}}, or the name of a primitive type. If it is a pointer
- type, the trailing asterisk should not be preceded by a space.
- \var{name} should be the name of the function (or function-like
- pre-processor macro), and \var{args} should give the types and
- names of the parameters. The names need to be given so they may
- be used in the description.
- \end{envdesc}
-
- \begin{envdesc}{cmemberdesc}{\p{container}\p{type}\p{name}}
- Description for a structure member. \var{container} should be
- the \keyword{typedef} name, if there is one, otherwise if should
- be \samp{struct \var{tag}}. The type of the member should given
- as \var{type}, and the name should be given as \var{name}. The
- text of the description should include the range of values
- allowed, how the value should be interpreted, and whether the
- value can be changed. References to structure members in text
- should use the \macro{member} macro.
- \end{envdesc}
-
- \begin{envdesc}{csimplemacrodesc}{\p{name}}
- Documentation for a ``simple'' macro. Simple macros are macros
- which are used for code expansion, but which do not take
- arguments so cannot be described as functions. This is not to
- be used for simple constant definitions. Examples of it's use
- in the Python documentation include
- \csimplemacro{PyObject_HEAD} and
- \csimplemacro{Py_BEGIN_ALLOW_THREADS}.
- \end{envdesc}
-
- \begin{envdesc}{ctypedesc}{\op{tag}\p{name}}
- Environment used to described a C type. The \var{name}
- parameter should be the \keyword{typedef} name. If the type is
- defined as a \keyword{struct} without a \keyword{typedef},
- \var{name} should have the form \code{struct \var{tag}}.
- \var{name} will be added to the index unless \var{tag} is
- provided, in which case \var{tag} will be used instead.
- \var{tag} should not be used for a \keyword{typedef} name.
- \end{envdesc}
-
- \begin{envdesc}{cvardesc}{\p{type}\p{name}}
- Description of a global C variable. \var{type} should be the
- \keyword{typedef} name, \code{struct \var{tag}}, or the name of
- a primitive type. If variable has a pointer type, the trailing
- asterisk should \emph{not} be preceded by a space.
- \end{envdesc}
-
- \begin{envdesc}{datadesc}{\p{name}}
- This environment is used to document global data in a module,
- including both variables and values used as ``defined
- constants.'' Class and object attributes are not documented
- using this environment.
- \end{envdesc}
- \begin{envdesc}{datadescni}{\p{name}}
- Like \env{datadesc}, but without creating any index entries.
- \end{envdesc}
-
- \begin{envdesc}{excclassdesc}{\p{name}\p{constructor parameters}}
- Descibe an exception defined by a class. \var{constructor
- parameters} should not include the \var{self} parameter or
- the parentheses used in the call syntax. To describe an
- exception class without describing the parameters to its
- constructor, use the \env{excdesc} environment.
- \end{envdesc}
-
- \begin{envdesc}{excdesc}{\p{name}}
- Describe an exception. In the case of class exceptions, the
- constructor parameters are not described; use \env{excclassdesc}
- to describe an exception class and its constructor.
- \end{envdesc}
-
- \begin{envdesc}{funcdesc}{\p{name}\p{parameters}}
- Describe a module-level function. \var{parameters} should
- not include the parentheses used in the call syntax. Object
- methods are not documented using this environment. Bound object
- methods placed in the module namespace as part of the public
- interface of the module are documented using this, as they are
- equivalent to normal functions for most purposes.
-
- The description should include information about the parameters
- required and how they are used (especially whether mutable
- objects passed as parameters are modified), side effects, and
- possible exceptions. A small example may be provided.
- \end{envdesc}
- \begin{envdesc}{funcdescni}{\p{name}\p{parameters}}
- Like \env{funcdesc}, but without creating any index entries.
- \end{envdesc}
-
- \begin{envdesc}{classdesc}{\p{name}\p{constructor parameters}}
- Describe a class and its constructor. \var{constructor
- parameters} should not include the \var{self} parameter or
- the parentheses used in the call syntax.
- \end{envdesc}
-
- \begin{envdesc}{classdesc*}{\p{name}}
- Describe a class without describing the constructor. This can
- be used to describe classes that are merely containers for
- attributes or which should never be instantiated or subclassed
- by user code.
- \end{envdesc}
-
- \begin{envdesc}{memberdesc}{\op{type name}\p{name}}
- Describe an object data attribute. The description should
- include information about the type of the data to be expected
- and whether it may be changed directly.
- \end{envdesc}
- \begin{envdesc}{memberdescni}{\op{type name}\p{name}}
- Like \env{memberdesc}, but without creating any index entries.
- \end{envdesc}
-
- \begin{envdesc}{methoddesc}{\op{type name}\p{name}\p{parameters}}
- Describe an object method. \var{parameters} should not include
- the \var{self} parameter or the parentheses used in the call
- syntax. The description should include similar information to
- that described for \env{funcdesc}.
- \end{envdesc}
- \begin{envdesc}{methoddescni}{\op{type name}\p{name}\p{parameters}}
- Like \env{methoddesc}, but without creating any index entries.
- \end{envdesc}
-
-
- \subsection{Showing Code Examples \label{showing-examples}}
-
- Examples of Python source code or interactive sessions are
- represented as \env{verbatim} environments. This environment
- is a standard part of \LaTeX{}. It is important to only use
- spaces for indentation in code examples since \TeX{} drops tabs
- instead of converting them to spaces.
-
- Representing an interactive session requires including the prompts
- and output along with the Python code. No special markup is
- required for interactive sessions. After the last line of input
- or output presented, there should not be an ``unused'' primary
- prompt; this is an example of what \emph{not} to do:
-
-\begin{verbatim}
->>> 1 + 1
-2
->>>
-\end{verbatim}
-
- Within the \env{verbatim} environment, characters special to
- \LaTeX{} do not need to be specially marked in any way. The entire
- example will be presented in a monospaced font; no attempt at
- ``pretty-printing'' is made, as the environment must work for
- non-Python code and non-code displays. There should be no blank
- lines at the top or bottom of any \env{verbatim} display.
-
- Longer displays of verbatim text may be included by storing the
- example text in an external file containing only plain text. The
- file may be included using the standard \macro{verbatiminput}
- macro; this macro takes a single argument naming the file
- containing the text. For example, to include the Python source
- file \file{example.py}, use:
-
-\begin{verbatim}
-\verbatiminput{example.py}
-\end{verbatim}
-
- Use of \macro{verbatiminput} allows easier use of special editing
- modes for the included file. The file should be placed in the
- same directory as the \LaTeX{} files for the document.
-
- The Python Documentation Special Interest Group has discussed a
- number of approaches to creating pretty-printed code displays and
- interactive sessions; see the Doc-SIG area on the Python Web site
- for more information on this topic.
-
-
- \subsection{Inline Markup \label{inline-markup}}
-
- The macros described in this section are used to mark just about
- anything interesting in the document text. They may be used in
- headings (though anything involving hyperlinks should be avoided
- there) as well as in the body text.
-
- \begin{macrodesc}{bfcode}{\p{text}}
- Like \macro{code}, but also makes the font bold-face.
- \end{macrodesc}
-
- \begin{macrodesc}{cdata}{\p{name}}
- The name of a C-language variable.
- \end{macrodesc}
-
- \begin{macrodesc}{cfunction}{\p{name}}
- The name of a C-language function. \var{name} should include the
- function name and the trailing parentheses.
- \end{macrodesc}
-
- \begin{macrodesc}{character}{\p{char}}
- A character when discussing the character rather than a one-byte
- string value. The character will be typeset as with \macro{samp}.
- \end{macrodesc}
-
- \begin{macrodesc}{citetitle}{\op{url}\p{title}}
- A title for a referenced publication. If \var{url} is specified,
- the title will be made into a hyperlink when formatted as HTML.
- \end{macrodesc}
-
- \begin{macrodesc}{class}{\p{name}}
- A class name; a dotted name may be used.
- \end{macrodesc}
-
- \begin{macrodesc}{code}{\p{text}}
- A short code fragment or literal constant value. Typically, it
- should not include any spaces since no quotation marks are
- added.
- \end{macrodesc}
-
- \begin{macrodesc}{constant}{\p{name}}
- The name of a ``defined'' constant. This may be a C-language
- \code{\#define} or a Python variable that is not intended to be
- changed.
- \end{macrodesc}
-
- \begin{macrodesc}{csimplemacro}{\p{name}}
- The name of a ``simple'' macro. Simple macros are macros
- which are used for code expansion, but which do not take
- arguments so cannot be described as functions. This is not to
- be used for simple constant definitions. Examples of it's use
- in the Python documentation include
- \csimplemacro{PyObject_HEAD} and
- \csimplemacro{Py_BEGIN_ALLOW_THREADS}.
- \end{macrodesc}
-
- \begin{macrodesc}{ctype}{\p{name}}
- The name of a C \keyword{typedef} or structure. For structures
- defined without a \keyword{typedef}, use \code{\e ctype\{struct
- struct_tag\}} to make it clear that the \keyword{struct} is
- required.
- \end{macrodesc}
-
- \begin{macrodesc}{deprecated}{\p{version}\p{what to do}}
- Declare whatever is being described as being deprecated starting
- with release \var{version}. The text given as \var{what to do}
- should recommend something to use instead. It should be
- complete sentences. The entire deprecation notice will be
- presented as a separate paragraph; it should either preceed or
- succeed the description of the deprecated feature.
- \end{macrodesc}
-
- \begin{macrodesc}{dfn}{\p{term}}
- Mark the defining instance of \var{term} in the text. (No index
- entries are generated.)
- \end{macrodesc}
-
- \begin{macrodesc}{e}{}
- Produces a backslash. This is convenient in \macro{code} and
- similar macros, and is only defined there. To create a
- backslash in ordinary text (such as the contents of the
- \macro{file} macro), use the standard \macro{textbackslash} macro.
- \end{macrodesc}
-
- \begin{macrodesc}{email}{\p{address}}
- An email address. Note that this is \emph{not} hyperlinked in
- any of the possible output formats. The domain name portion of
- the address should be lower case.
- \end{macrodesc}
-
- \begin{macrodesc}{emph}{\p{text}}
- Emphasized text; this will be presented in an italic font.
- \end{macrodesc}
-
- \begin{macrodesc}{envvar}{\p{name}}
- An environment variable. Index entries are generated.
- \end{macrodesc}
-
- \begin{macrodesc}{exception}{\p{name}}
- The name of an exception. A dotted name may be used.
- \end{macrodesc}
-
- \begin{macrodesc}{file}{\p{file or dir}}
- The name of a file or directory. In the PDF and PostScript
- outputs, single quotes and a font change are used to indicate
- the file name, but no quotes are used in the HTML output.
- \warning{The \macro{file} macro cannot be used in the
- content of a section title due to processing limitations.}
- \end{macrodesc}
-
- \begin{macrodesc}{filenq}{\p{file or dir}}
- Like \macro{file}, but single quotes are never used. This can
- be used in conjunction with tables if a column will only contain
- file or directory names.
- \warning{The \macro{filenq} macro cannot be used in the
- content of a section title due to processing limitations.}
- \end{macrodesc}
-
- \begin{macrodesc}{function}{\p{name}}
- The name of a Python function; dotted names may be used.
- \end{macrodesc}
-
- \begin{macrodesc}{infinity}{}
- The symbol for mathematical infinity: \infinity. Some Web
- browsers are not able to render the HTML representation of this
- symbol properly, but support is growing.
- \end{macrodesc}
-
- \begin{macrodesc}{kbd}{\p{key sequence}}
- Mark a sequence of keystrokes. What form \var{key sequence}
- takes may depend on platform- or application-specific
- conventions. When there are no relevant conventions, the names
- of modifier keys should be spelled out, to improve accessibility
- for new users and non-native speakers. For example, an
- \program{xemacs} key sequence may be marked like
- \code{\e kbd\{C-x C-f\}}, but without reference to a specific
- application or platform, the same sequence should be marked as
- \code{\e kbd\{Control-x Control-f\}}.
- \end{macrodesc}
-
- \begin{macrodesc}{keyword}{\p{name}}
- The name of a keyword in a programming language.
- \end{macrodesc}
-
- \begin{macrodesc}{mailheader}{\p{name}}
- The name of an \rfc{822}-style mail header. This markup does
- not imply that the header is being used in an email message, but
- can be used to refer to any header of the same ``style.'' This
- is also used for headers defined by the various MIME
- specifications. The header name should be entered in the same
- way it would normally be found in practice, with the
- camel-casing conventions being preferred where there is more
- than one common usage. The colon which follows the name of the
- header should not be included.
- For example: \code{\e mailheader\{Content-Type\}}.
- \end{macrodesc}
-
- \begin{macrodesc}{makevar}{\p{name}}
- The name of a \program{make} variable.
- \end{macrodesc}
-
- \begin{macrodesc}{manpage}{\p{name}\p{section}}
- A reference to a \UNIX{} manual page.
- \end{macrodesc}
-
- \begin{macrodesc}{member}{\p{name}}
- The name of a data attribute of an object.
- \end{macrodesc}
-
- \begin{macrodesc}{method}{\p{name}}
- The name of a method of an object. \var{name} should include the
- method name and the trailing parentheses. A dotted name may be
- used.
- \end{macrodesc}
-
- \begin{macrodesc}{mimetype}{\p{name}}
- The name of a MIME type, or a component of a MIME type (the
- major or minor portion, taken alone).
- \end{macrodesc}
-
- \begin{macrodesc}{module}{\p{name}}
- The name of a module; a dotted name may be used. This should
- also be used for package names.
- \end{macrodesc}
-
- \begin{macrodesc}{newsgroup}{\p{name}}
- The name of a Usenet newsgroup.
- \end{macrodesc}
-
- \begin{macrodesc}{note}{\p{text}}
- An especially important bit of information about an API that a
- user should be aware of when using whatever bit of API the
- note pertains to. This should be the last thing in the
- paragraph as the end of the note is not visually marked in
- any way. The content of \var{text} should be written in
- complete sentences and include all appropriate punctuation.
- \end{macrodesc}
-
- \begin{macrodesc}{pep}{\p{number}}
- A reference to a Python Enhancement Proposal. This generates
- appropriate index entries. The text \samp{PEP \var{number}} is
- generated; in the HTML output, this text is a hyperlink to an
- online copy of the specified PEP.
- \end{macrodesc}
-
- \begin{macrodesc}{plusminus}{}
- The symbol for indicating a value that may take a positive or
- negative value of a specified magnitude, typically represented
- by a plus sign placed over a minus sign. For example:
- \code{\e plusminus 3\%{}}.
- \end{macrodesc}
-
- \begin{macrodesc}{program}{\p{name}}
- The name of an executable program. This may differ from the
- file name for the executable for some platforms. In particular,
- the \file{.exe} (or other) extension should be omitted for
- Windows programs.
- \end{macrodesc}
-
- \begin{macrodesc}{programopt}{\p{option}}
- A command-line option to an executable program. Use this only
- for ``short'' options, and include the leading hyphen.
- \end{macrodesc}
-
- \begin{macrodesc}{longprogramopt}{\p{option}}
- A long command-line option to an executable program. This
- should only be used for long option names which will be prefixed
- by two hyphens; the hyphens should not be provided as part of
- \var{option}.
- \end{macrodesc}
-
- \begin{macrodesc}{refmodule}{\op{key}\p{name}}
- Like \macro{module}, but create a hyperlink to the documentation
- for the named module. Note that the corresponding
- \macro{declaremodule} must be in the same document. If the
- \macro{declaremodule} defines a module key different from the
- module name, it must also be provided as \var{key} to the
- \macro{refmodule} macro.
- \end{macrodesc}
-
- \begin{macrodesc}{regexp}{\p{string}}
- Mark a regular expression.
- \end{macrodesc}
-
- \begin{macrodesc}{rfc}{\p{number}}
- A reference to an Internet Request for Comments. This generates
- appropriate index entries. The text \samp{RFC \var{number}} is
- generated; in the HTML output, this text is a hyperlink to an
- online copy of the specified RFC.
- \end{macrodesc}
-
- \begin{macrodesc}{samp}{\p{text}}
- A short code sample, but possibly longer than would be given
- using \macro{code}. Since quotation marks are added, spaces are
- acceptable.
- \end{macrodesc}
-
- \begin{macrodesc}{shortversion}{}
- The ``short'' version number of the documented software, as
- specified using the \macro{setshortversion} macro in the
- preamble. For Python, the short version number for a release is
- the first three characters of the \code{sys.version} value. For
- example, versions 2.0b1 and 2.0.1 both have a short version of
- 2.0. This may not apply for all packages; if
- \macro{setshortversion} is not used, this produces an empty
- expansion. See also the \macro{version} macro.
- \end{macrodesc}
-
- \begin{macrodesc}{strong}{\p{text}}
- Strongly emphasized text; this will be presented using a bold
- font.
- \end{macrodesc}
-
- \begin{macrodesc}{ulink}{\p{text}\p{url}}
- A hypertext link with a target specified by a URL, but for which
- the link text should not be the title of the resource. For
- resources being referenced by name, use the \macro{citetitle}
- macro. Not all formatted versions support arbitrary hypertext
- links. Note that many characters are special to \LaTeX{} and
- this macro does not always do the right thing. In particular,
- the tilde character (\character{\~}) is mis-handled; encoding it
- as a hex-sequence does work, use \samp{\%7e} in place of the
- tilde character.
- \end{macrodesc}
-
- \begin{macrodesc}{url}{\p{url}}
- A URL (or URN). The URL will be presented as text. In the HTML
- and PDF formatted versions, the URL will also be a hyperlink.
- This can be used when referring to external resources without
- specific titles; references to resources which have titles
- should be marked using the \macro{citetitle} macro. See the
- comments about special characters in the description of the
- \macro{ulink} macro for special considerations.
- \end{macrodesc}
-
- \begin{macrodesc}{var}{\p{name}}
- The name of a variable or formal parameter in running text.
- \end{macrodesc}
-
- \begin{macrodesc}{version}{}
- The version number of the described software, as specified using
- \macro{release} in the preamble. See also the
- \macro{shortversion} macro.
- \end{macrodesc}
-
- \begin{macrodesc}{versionadded}{\op{explanation}\p{version}}
- The version of Python which added the described feature to the
- library or C API. \var{explanation} should be a \emph{brief}
- explanation of the change consisting of a capitalized sentence
- fragment; a period will be appended by the formatting process.
- This is typically added to the end of the first paragraph of the
- description before any availability notes. The location should
- be selected so the explanation makes sense and may vary as
- needed.
- \end{macrodesc}
-
- \begin{macrodesc}{versionchanged}{\op{explanation}\p{version}}
- The version of Python in which the named feature was changed in
- some way (new parameters, changed side effects, etc.).
- \var{explanation} should be a \emph{brief} explanation of the
- change consisting of a capitalized sentence fragment; a
- period will be appended by the formatting process.
- This is typically added to the end of the first paragraph of the
- description before any availability notes and after
- \macro{versionadded}. The location should be selected so the
- explanation makes sense and may vary as needed.
- \end{macrodesc}
-
- \begin{macrodesc}{warning}{\p{text}}
- An important bit of information about an API that a user should
- be very aware of when using whatever bit of API the warning
- pertains to. This should be the last thing in the paragraph as
- the end of the warning is not visually marked in any way. The
- content of \var{text} should be written in complete sentences
- and include all appropriate punctuation. This differs from
- \macro{note} in that it is recommended over \macro{note} for
- information regarding security.
- \end{macrodesc}
-
-
- \subsection{Miscellaneous Text Markup \label{misc-text-markup}}
-
- In addition to the inline markup, some additional ``block'' markup
- is defined to make it easier to bring attention to various bits of
- text. The markup described here serves this purpose, and is
- intended to be used when marking one or more paragraphs or other
- block constructs (such as \env{verbatim} environments).
-
- \begin{envdesc}{notice}{\op{type}}
- Label some paragraphs as being worthy of additional attention from
- the reader. What sort of attention is warrented can be indicated
- by specifying the \var{type} of the notice. The only values
- defined for \var{type} are \code{note} and \code{warning}; these
- are equivalent in intent to the inline markup of the same name.
- If \var{type} is omitted, \code{note} is used. Additional values
- may be defined in the future.
- \end{envdesc}
-
-
- \subsection{Module-specific Markup \label{module-markup}}
-
- The markup described in this section is used to provide information
- about a module being documented. A typical use of this markup
- appears at the top of the section used to document a module. A
- typical example might look like this:
-
-\begin{verbatim}
-\section{\module{spam} ---
- Access to the SPAM facility}
-
-\declaremodule{extension}{spam}
- \platform{Unix}
-\modulesynopsis{Access to the SPAM facility of \UNIX.}
-\moduleauthor{Jane Doe}{jane.doe@frobnitz.org}
-\end{verbatim}
-
- Python packages\index{packages} --- collections of modules that can
- be described as a unit --- are documented using the same markup as
- modules. The name for a module in a package should be typed in
- ``fully qualified'' form (it should include the package name).
- For example, a module ``foo'' in package ``bar'' should be marked as
- \code{\e module\{bar.foo\}}, and the beginning of the reference
- section would appear as:
-
-\begin{verbatim}
-\section{\module{bar.foo} ---
- Module from the \module{bar} package}
-
-\declaremodule{extension}{bar.foo}
-\modulesynopsis{Nifty module from the \module{bar} package.}
-\moduleauthor{Jane Doe}{jane.doe@frobnitz.org}
-\end{verbatim}
-
- Note that the name of a package is also marked using
- \macro{module}.
-
- \begin{macrodesc}{declaremodule}{\op{key}\p{type}\p{name}}
- Requires two parameters: module type (\samp{standard},
- \samp{builtin}, \samp{extension}, or \samp{}), and the module
- name. An optional parameter should be given as the basis for the
- module's ``key'' used for linking to or referencing the section.
- The ``key'' should only be given if the module's name contains any
- underscores, and should be the name with the underscores stripped.
- Note that the \var{type} parameter must be one of the values
- listed above or an error will be printed. For modules which are
- contained in packages, the fully-qualified name should be given as
- \var{name} parameter. This should be the first thing after the
- \macro{section} used to introduce the module.
- \end{macrodesc}
-
- \begin{macrodesc}{platform}{\p{specifier}}
- Specifies the portability of the module. \var{specifier} is a
- comma-separated list of keys that specify what platforms the
- module is available on. The keys are short identifiers;
- examples that are in use include \samp{IRIX}, \samp{Mac},
- \samp{Windows}, and \samp{Unix}. It is important to use a key
- which has already been used when applicable. This is used to
- provide annotations in the Module Index and the HTML and GNU info
- output.
- \end{macrodesc}
-
- \begin{macrodesc}{modulesynopsis}{\p{text}}
- The \var{text} is a short, ``one line'' description of the
- module that can be used as part of the chapter introduction.
- This is must be placed after \macro{declaremodule}.
- The synopsis is used in building the contents of the table
- inserted as the \macro{localmoduletable}. No text is
- produced at the point of the markup.
- \end{macrodesc}
-
- \begin{macrodesc}{moduleauthor}{\p{name}\p{email}}
- This macro is used to encode information about who authored a
- module. This is currently not used to generate output, but can be
- used to help determine the origin of the module.
- \end{macrodesc}
-
-
- \subsection{Library-level Markup \label{library-markup}}
-
- This markup is used when describing a selection of modules. For
- example, the \citetitle[../mac/mac.html]{Macintosh Library
- Modules} document uses this to help provide an overview of the
- modules in the collection, and many chapters in the
- \citetitle[../lib/lib.html]{Python Library Reference} use it for
- the same purpose.
-
- \begin{macrodesc}{localmoduletable}{}
- If a \file{.syn} file exists for the current
- chapter (or for the entire document in \code{howto} documents), a
- \env{synopsistable} is created with the contents loaded from the
- \file{.syn} file.
- \end{macrodesc}
-
-
- \subsection{Table Markup \label{table-markup}}
-
- There are three general-purpose table environments defined which
- should be used whenever possible. These environments are defined
- to provide tables of specific widths and some convenience for
- formatting. These environments are not meant to be general
- replacements for the standard \LaTeX{} table environments, but can
- be used for an advantage when the documents are processed using
- the tools for Python documentation processing. In particular, the
- generated HTML looks good! There is also an advantage for the
- eventual conversion of the documentation to XML (see section
- \ref{futures}, ``Future Directions'').
-
- Each environment is named \env{table\var{cols}}, where \var{cols}
- is the number of columns in the table specified in lower-case
- Roman numerals. Within each of these environments, an additional
- macro, \macro{line\var{cols}}, is defined, where \var{cols}
- matches the \var{cols} value of the corresponding table
- environment. These are supported for \var{cols} values of
- \code{ii}, \code{iii}, and \code{iv}. These environments are all
- built on top of the \env{tabular} environment. Variants based on
- the \env{longtable} environment are also provided.
-
- Note that all tables in the standard Python documentation use
- vertical lines between columns, and this must be specified in the
- markup for each table. A general border around the outside of the
- table is not used, but would be the responsibility of the
- processor; the document markup should not include an exterior
- border.
-
- The \env{longtable}-based variants of the table environments are
- formatted with extra space before and after, so should only be
- used on tables which are long enough that splitting over multiple
- pages is reasonable; tables with fewer than twenty rows should
- never by marked using the long flavors of the table environments.
- The header row is repeated across the top of each part of the
- table.
-
- \begin{envdesc}{tableii}{\p{colspec}\p{col1font}\p{heading1}\p{heading2}}
- Create a two-column table using the \LaTeX{} column specifier
- \var{colspec}. The column specifier should indicate vertical
- bars between columns as appropriate for the specific table, but
- should not specify vertical bars on the outside of the table
- (that is considered a stylesheet issue). The \var{col1font}
- parameter is used as a stylistic treatment of the first column
- of the table: the first column is presented as
- \code{\e\var{col1font}\{column1\}}. To avoid treating the first
- column specially, \var{col1font} may be \samp{textrm}. The
- column headings are taken from the values \var{heading1} and
- \var{heading2}.
- \end{envdesc}
-
- \begin{envdesc}{longtableii}{\unspecified}
- Like \env{tableii}, but produces a table which may be broken
- across page boundaries. The parameters are the same as for
- \env{tableii}.
- \end{envdesc}
-
- \begin{macrodesc}{lineii}{\p{column1}\p{column2}}
- Create a single table row within a \env{tableii} or
- \env{longtableii} environment.
- The text for the first column will be generated by applying the
- macro named by the \var{col1font} value when the \env{tableii}
- was opened.
- \end{macrodesc}
-
- \begin{envdesc}{tableiii}{\p{colspec}\p{col1font}\p{heading1}\p{heading2}\p{heading3}}
- Like the \env{tableii} environment, but with a third column.
- The heading for the third column is given by \var{heading3}.
- \end{envdesc}
-
- \begin{envdesc}{longtableiii}{\unspecified}
- Like \env{tableiii}, but produces a table which may be broken
- across page boundaries. The parameters are the same as for
- \env{tableiii}.
- \end{envdesc}
-
- \begin{macrodesc}{lineiii}{\p{column1}\p{column2}\p{column3}}
- Like the \macro{lineii} macro, but with a third column. The
- text for the third column is given by \var{column3}.
- \end{macrodesc}
-
- \begin{envdesc}{tableiv}{\p{colspec}\p{col1font}\p{heading1}\p{heading2}\p{heading3}\p{heading4}}
- Like the \env{tableiii} environment, but with a fourth column.
- The heading for the fourth column is given by \var{heading4}.
- \end{envdesc}
-
- \begin{envdesc}{longtableiv}{\unspecified}
- Like \env{tableiv}, but produces a table which may be broken
- across page boundaries. The parameters are the same as for
- \env{tableiv}.
- \end{envdesc}
-
- \begin{macrodesc}{lineiv}{\p{column1}\p{column2}\p{column3}\p{column4}}
- Like the \macro{lineiii} macro, but with a fourth column. The
- text for the fourth column is given by \var{column4}.
- \end{macrodesc}
-
- \begin{envdesc}{tablev}{\p{colspec}\p{col1font}\p{heading1}\p{heading2}\p{heading3}\p{heading4}\p{heading5}}
- Like the \env{tableiv} environment, but with a fifth column.
- The heading for the fifth column is given by \var{heading5}.
- \end{envdesc}
-
- \begin{envdesc}{longtablev}{\unspecified}
- Like \env{tablev}, but produces a table which may be broken
- across page boundaries. The parameters are the same as for
- \env{tablev}.
- \end{envdesc}
-
- \begin{macrodesc}{linev}{\p{column1}\p{column2}\p{column3}\p{column4}\p{column5}}
- Like the \macro{lineiv} macro, but with a fifth column. The
- text for the fifth column is given by \var{column5}.
- \end{macrodesc}
-
-
- An additional table-like environment is \env{synopsistable}. The
- table generated by this environment contains two columns, and each
- row is defined by an alternate definition of
- \macro{modulesynopsis}. This environment is not normally used by
- authors, but is created by the \macro{localmoduletable} macro.
-
- Here is a small example of a table given in the documentation for
- the \module{warnings} module; markup inside the table cells is
- minimal so the markup for the table itself is readily discernable.
- Here is the markup for the table:
-
-\begin{verbatim}
-\begin{tableii}{l|l}{exception}{Class}{Description}
- \lineii{Warning}
- {This is the base class of all warning category classes. It
- is a subclass of \exception{Exception}.}
- \lineii{UserWarning}
- {The default category for \function{warn()}.}
- \lineii{DeprecationWarning}
- {Base category for warnings about deprecated features.}
- \lineii{SyntaxWarning}
- {Base category for warnings about dubious syntactic
- features.}
- \lineii{RuntimeWarning}
- {Base category for warnings about dubious runtime features.}
- \lineii{FutureWarning}
- {Base category for warnings about constructs that will change
- semantically in the future.}
-\end{tableii}
-\end{verbatim}
-
- Here is the resulting table:
-
-\begin{tableii}{l|l}{exception}{Class}{Description}
- \lineii{Warning}
- {This is the base class of all warning category classes. It
- is a subclass of \exception{Exception}.}
- \lineii{UserWarning}
- {The default category for \function{warn()}.}
- \lineii{DeprecationWarning}
- {Base category for warnings about deprecated features.}
- \lineii{SyntaxWarning}
- {Base category for warnings about dubious syntactic
- features.}
- \lineii{RuntimeWarning}
- {Base category for warnings about dubious runtime features.}
-\end{tableii}
-
- Note that the class names are implicitly marked using the
- \macro{exception} macro, since that is given as the \var{col1font}
- value for the \env{tableii} environment. To create a table using
- different markup for the first column, use \code{textrm} for the
- \var{col1font} value and mark each entry individually.
-
- To add a horizontal line between vertical sections of a table, use
- the standard \macro{hline} macro between the rows which should be
- separated:
-
-\begin{verbatim}
-\begin{tableii}{l|l}{constant}{Language}{Audience}
- \lineii{APL}{Masochists.}
- \lineii{BASIC}{First-time programmers on PC hardware.}
- \lineii{C}{\UNIX{} \&\ Linux kernel developers.}
- \hline
- \lineii{Python}{Everyone!}
-\end{tableii}
-\end{verbatim}
-
- Note that not all presentation formats are capable of displaying a
- horizontal rule in this position. This is how the table looks in
- the format you're reading now:
-
-\begin{tableii}{l|l}{constant}{Language}{Audience}
- \lineii{APL}{Masochists.}
- \lineii{C}{\UNIX{} \&\ Linux kernel developers.}
- \lineii{JavaScript}{Web developers.}
- \hline
- \lineii{Python}{Everyone!}
-\end{tableii}
-
-
- \subsection{Reference List Markup \label{references}}
-
- Many sections include a list of references to module documentation
- or external documents. These lists are created using the
- \env{seealso} or \env{seealso*} environments. These environments
- define some additional macros to support creating reference
- entries in a reasonable manner.
-
- The \env{seealso} environment is typically placed in a section
- just before any sub-sections. This is done to ensure that
- reference links related to the section are not hidden in a
- subsection in the hypertext renditions of the documentation. For
- the HTML output, it is shown as a ``side bar,'' boxed off from the
- main flow of the text. The \env{seealso*} environment is
- different in that it should be used when a list of references is
- being presented as part of the primary content; it is not
- specially set off from the text.
-
- \begin{envdesc}{seealso}{}
- This environment creates a ``See also:'' heading and defines the
- markup used to describe individual references.
- \end{envdesc}
-
- \begin{envdesc}{seealso*}{}
- This environment is used to create a list of references which
- form part of the main content. It is not given a special
- header and is not set off from the main flow of the text. It
- provides the same additional markup used to describe individual
- references.
- \end{envdesc}
-
- For each of the following macros, \var{why} should be one or more
- complete sentences, starting with a capital letter (unless it
- starts with an identifier, which should not be modified), and
- ending with the apropriate punctuation.
-
- These macros are only defined within the content of the
- \env{seealso} and \env{seealso*} environments.
-
- \begin{macrodesc}{seemodule}{\op{key}\p{name}\p{why}}
- Refer to another module. \var{why} should be a brief
- explanation of why the reference may be interesting. The module
- name is given in \var{name}, with the link key given in
- \var{key} if necessary. In the HTML and PDF conversions, the
- module name will be a hyperlink to the referred-to module.
- \note{The module must be documented in the same
- document (the corresponding \macro{declaremodule} is required).}
- \end{macrodesc}
-
- \begin{macrodesc}{seepep}{\p{number}\p{title}\p{why}}
- Refer to an Python Enhancement Proposal (PEP). \var{number}
- should be the official number assigned by the PEP Editor,
- \var{title} should be the human-readable title of the PEP as
- found in the official copy of the document, and \var{why} should
- explain what's interesting about the PEP. This should be used
- to refer the reader to PEPs which specify interfaces or language
- features relevant to the material in the annotated section of the
- documentation.
- \end{macrodesc}
-
- \begin{macrodesc}{seerfc}{\p{number}\p{title}\p{why}}
- Refer to an IETF Request for Comments (RFC). Otherwise very
- similar to \macro{seepep}. This should be used
- to refer the reader to PEPs which specify protocols or data
- formats relevant to the material in the annotated section of the
- documentation.
- \end{macrodesc}
-
- \begin{macrodesc}{seetext}{\p{text}}
- Add arbitrary text \var{text} to the ``See also:'' list. This
- can be used to refer to off-line materials or on-line materials
- using the \macro{url} macro. This should consist of one or more
- complete sentences.
- \end{macrodesc}
-
- \begin{macrodesc}{seetitle}{\op{url}\p{title}\p{why}}
- Add a reference to an external document named \var{title}. If
- \var{url} is given, the title is made a hyperlink in the HTML
- version of the documentation, and displayed below the title in
- the typeset versions of the documentation.
- \end{macrodesc}
-
- \begin{macrodesc}{seeurl}{\p{url}\p{why}}
- References to specific on-line resources should be given using
- the \macro{seeurl} macro if they don't have a meaningful title.
- Online documents which have identifiable titles should be
- referenced using the \macro{seetitle} macro, using the optional
- parameter to that macro to provide the URL.
- \end{macrodesc}
-
-
- \subsection{Index-generating Markup \label{indexing}}
-
- Effective index generation for technical documents can be very
- difficult, especially for someone familiar with the topic but not
- the creation of indexes. Much of the difficulty arises in the
- area of terminology: including the terms an expert would use for a
- concept is not sufficient. Coming up with the terms that a novice
- would look up is fairly difficult for an author who, typically, is
- an expert in the area she is writing on.
-
- The truly difficult aspects of index generation are not areas with
- which the documentation tools can help. However, ease
- of producing the index once content decisions are made is within
- the scope of the tools. Markup is provided which the processing
- software is able to use to generate a variety of kinds of index
- entry with minimal effort. Additionally, many of the environments
- described in section \ref{info-units}, ``Information Units,'' will
- generate appropriate entries into the general and module indexes.
-
- The following macro can be used to control the generation of index
- data, and should be used in the document preamble:
-
- \begin{macrodesc}{makemodindex}{}
- This should be used in the document preamble if a ``Module
- Index'' is desired for a document containing reference material
- on many modules. This causes a data file
- \code{lib\var{jobname}.idx} to be created from the
- \macro{declaremodule} macros. This file can be processed by the
- \program{makeindex} program to generate a file which can be
- \macro{input} into the document at the desired location of the
- module index.
- \end{macrodesc}
-
- There are a number of macros that are useful for adding index
- entries for particular concepts, many of which are specific to
- programming languages or even Python.
-
- \begin{macrodesc}{bifuncindex}{\p{name}}
- Add an index entry referring to a built-in function named
- \var{name}; parentheses should not be included after
- \var{name}.
- \end{macrodesc}
-
- \begin{macrodesc}{exindex}{\p{exception}}
- Add a reference to an exception named \var{exception}. The
- exception should be class-based.
- \end{macrodesc}
-
- \begin{macrodesc}{kwindex}{\p{keyword}}
- Add a reference to a language keyword (not a keyword parameter
- in a function or method call).
- \end{macrodesc}
-
- \begin{macrodesc}{obindex}{\p{object type}}
- Add an index entry for a built-in object type.
- \end{macrodesc}
-
- \begin{macrodesc}{opindex}{\p{operator}}
- Add a reference to an operator, such as \samp{+}.
- \end{macrodesc}
-
- \begin{macrodesc}{refmodindex}{\op{key}\p{module}}
- Add an index entry for module \var{module}; if \var{module}
- contains an underscore, the optional parameter \var{key} should
- be provided as the same string with underscores removed. An
- index entry ``\var{module} (module)'' will be generated. This
- is intended for use with non-standard modules implemented in
- Python.
- \end{macrodesc}
-
- \begin{macrodesc}{refexmodindex}{\op{key}\p{module}}
- As for \macro{refmodindex}, but the index entry will be
- ``\var{module} (extension module).'' This is intended for use
- with non-standard modules not implemented in Python.
- \end{macrodesc}
-
- \begin{macrodesc}{refbimodindex}{\op{key}\p{module}}
- As for \macro{refmodindex}, but the index entry will be
- ``\var{module} (built-in module).'' This is intended for use
- with standard modules not implemented in Python.
- \end{macrodesc}
-
- \begin{macrodesc}{refstmodindex}{\op{key}\p{module}}
- As for \macro{refmodindex}, but the index entry will be
- ``\var{module} (standard module).'' This is intended for use
- with standard modules implemented in Python.
- \end{macrodesc}
-
- \begin{macrodesc}{stindex}{\p{statement}}
- Add an index entry for a statement type, such as \keyword{print}
- or \keyword{try}/\keyword{finally}.
-
- XXX Need better examples of difference from \macro{kwindex}.
- \end{macrodesc}
-
-
- Additional macros are provided which are useful for conveniently
- creating general index entries which should appear at many places
- in the index by rotating a list of words. These are simple macros
- that simply use \macro{index} to build some number of index
- entries. Index entries build using these macros contain both
- primary and secondary text.
-
- \begin{macrodesc}{indexii}{\p{word1}\p{word2}}
- Build two index entries. This is exactly equivalent to using
- \code{\e index\{\var{word1}!\var{word2}\}} and
- \code{\e index\{\var{word2}!\var{word1}\}}.
- \end{macrodesc}
-
- \begin{macrodesc}{indexiii}{\p{word1}\p{word2}\p{word3}}
- Build three index entries. This is exactly equivalent to using
- \code{\e index\{\var{word1}!\var{word2} \var{word3}\}},
- \code{\e index\{\var{word2}!\var{word3}, \var{word1}\}}, and
- \code{\e index\{\var{word3}!\var{word1} \var{word2}\}}.
- \end{macrodesc}
-
- \begin{macrodesc}{indexiv}{\p{word1}\p{word2}\p{word3}\p{word4}}
- Build four index entries. This is exactly equivalent to using
- \code{\e index\{\var{word1}!\var{word2} \var{word3} \var{word4}\}},
- \code{\e index\{\var{word2}!\var{word3} \var{word4}, \var{word1}\}},
- \code{\e index\{\var{word3}!\var{word4}, \var{word1} \var{word2}\}},
- and
- \code{\e index\{\var{word4}!\var{word1} \var{word2} \var{word3}\}}.
- \end{macrodesc}
-
- \subsection{Grammar Production Displays \label{grammar-displays}}
-
- Special markup is available for displaying the productions of a
- formal grammar. The markup is simple and does not attempt to
- model all aspects of BNF (or any derived forms), but provides
- enough to allow context-free grammars to be displayed in a way
- that causes uses of a symbol to be rendered as hyperlinks to the
- definition of the symbol. There is one environment and a pair of
- macros:
-
- \begin{envdesc}{productionlist}{\op{language}}
- This environment is used to enclose a group of productions. The
- two macros are only defined within this environment. If a
- document descibes more than one language, the optional parameter
- \var{language} should be used to distinguish productions between
- languages. The value of the parameter should be a short name
- that can be used as part of a filename; colons or other
- characters that can't be used in filename across platforms
- should be included.
- \end{envdesc}
-
- \begin{macrodesc}{production}{\p{name}\p{definition}}
- A production rule in the grammar. The rule defines the symbol
- \var{name} to be \var{definition}. \var{name} should not
- contain any markup, and the use of hyphens in a document which
- supports more than one grammar is undefined. \var{definition}
- may contain \macro{token} macros and any additional content
- needed to describe the grammatical model of \var{symbol}. Only
- one \macro{production} may be used to define a symbol ---
- multiple definitions are not allowed.
- \end{macrodesc}
-
- \begin{macrodesc}{token}{\p{name}}
- The name of a symbol defined by a \macro{production} macro, used
- in the \var{definition} of a symbol. Where possible, this will
- be rendered as a hyperlink to the definition of the symbol
- \var{name}.
- \end{macrodesc}
-
- Note that the entire grammar does not need to be defined in a
- single \env{productionlist} environment; any number of
- groupings may be used to describe the grammar. Every use of the
- \macro{token} must correspond to a \macro{production}.
-
- The following is an example taken from the
- \citetitle[../ref/identifiers.html]{Python Reference Manual}:
-
-\begin{verbatim}
-\begin{productionlist}
- \production{identifier}
- {(\token{letter}|"_") (\token{letter} | \token{digit} | "_")*}
- \production{letter}
- {\token{lowercase} | \token{uppercase}}
- \production{lowercase}
- {"a"..."z"}
- \production{uppercase}
- {"A"..."Z"}
- \production{digit}
- {"0"..."9"}
-\end{productionlist}
-\end{verbatim}
-
-
-\subsection{Graphical Interface Components \label{gui-markup}}
-
- The components of graphical interfaces will be assigned markup, but
- most of the specifics have not been determined.
-
- \begin{macrodesc}{menuselection}{\p{menupath}}
- Menu selections should be marked using a combination of
- \macro{menuselection} and \macro{sub}. This macro is used to mark
- a complete sequence of menu selections, including selecting
- submenus and choosing a specific operation, or any subsequence of
- such a sequence. The names of individual selections should be
- separated by occurances of \macro{sub}.
-
- For example, to mark the selection ``\menuselection{Start \sub
- Programs}'', use this markup:
-
-\begin{verbatim}
-\menuselection{Start \sub Programs}
-\end{verbatim}
-
- When including a selection that includes some trailing indicator,
- such as the ellipsis some operating systems use to indicate that
- the command opens a dialog, the indicator should be omitted from
- the selection name.
- \end{macrodesc}
-
- \begin{macrodesc}{sub}{}
- Separator for menu selections that include multiple levels. This
- macro is only defined within the context of the
- \macro{menuselection} macro.
- \end{macrodesc}
-
-
-\section{Processing Tools \label{tools}}
-
- \subsection{External Tools \label{tools-external}}
-
- Many tools are needed to be able to process the Python
- documentation if all supported formats are required. This
- section lists the tools used and when each is required. Consult
- the \file{Doc/README} file to see if there are specific version
- requirements for any of these.
-
- \begin{description}
- \item[\program{dvips}]
- This program is a typical part of \TeX{} installations. It is
- used to generate PostScript from the ``device independent''
- \file{.dvi} files. It is needed for the conversion to
- PostScript.
-
- \item[\program{emacs}]
- Emacs is the kitchen sink of programmers' editors, and a damn
- fine kitchen sink it is. It also comes with some of the
- processing needed to support the proper menu structures for
- Texinfo documents when an info conversion is desired. This is
- needed for the info conversion. Using \program{xemacs}
- instead of FSF \program{emacs} may lead to instability in the
- conversion, but that's because nobody seems to maintain the
- Emacs Texinfo code in a portable manner.
-
- \item[\program{latex}]
- \LaTeX{} is a large and extensible macro package by Leslie
- Lamport, based on \TeX, a world-class typesetter by Donald
- Knuth. It is used for the conversion to PostScript, and is
- needed for the HTML conversion as well (\LaTeX2HTML requires
- one of the intermediate files it creates).
-
- \item[\program{latex2html}]
- Probably the longest Perl script anyone ever attempted to
- maintain. This converts \LaTeX{} documents to HTML documents,
- and does a pretty reasonable job. It is required for the
- conversions to HTML and GNU info.
-
- \item[\program{lynx}]
- This is a text-mode Web browser which includes an
- HTML-to-plain text conversion. This is used to convert
- \code{howto} documents to text.
-
- \item[\program{make}]
- Just about any version should work for the standard documents,
- but GNU \program{make} is required for the experimental
- processes in \file{Doc/tools/sgmlconv/}, at least while
- they're experimental. This is not required for running the
- \program{mkhowto} script.
-
- \item[\program{makeindex}]
- This is a standard program for converting \LaTeX{} index data
- to a formatted index; it should be included with all \LaTeX{}
- installations. It is needed for the PDF and PostScript
- conversions.
-
- \item[\program{makeinfo}]
- GNU \program{makeinfo} is used to convert Texinfo documents to
- GNU info files. Since Texinfo is used as an intermediate
- format in the info conversion, this program is needed in that
- conversion.
-
- \item[\program{pdflatex}]
- pdf\TeX{} is a relatively new variant of \TeX, and is used to
- generate the PDF version of the manuals. It is typically
- installed as part of most of the large \TeX{} distributions.
- \program{pdflatex} is pdf\TeX{} using the \LaTeX{} format.
-
- \item[\program{perl}]
- Perl is required for \LaTeX2HTML{} and one of the scripts used
- to post-process \LaTeX2HTML output, as well as the
- HTML-to-Texinfo conversion. This is required for
- the HTML and GNU info conversions.
-
- \item[\program{python}]
- Python is used for many of the scripts in the
- \file{Doc/tools/} directory; it is required for all
- conversions. This shouldn't be a problem if you're interested
- in writing documentation for Python!
- \end{description}
-
-
- \subsection{Internal Tools \label{tools-internal}}
-
- This section describes the various scripts that are used to
- implement various stages of document processing or to orchestrate
- entire build sequences. Most of these tools are only useful
- in the context of building the standard documentation, but some
- are more general.
-
- \begin{description}
- \item[\program{mkhowto}]
- This is the primary script used to format third-party
- documents. It contains all the logic needed to ``get it
- right.'' The proper way to use this script is to make a
- symbolic link to it or run it in place; the actual script file
- must be stored as part of the documentation source tree,
- though it may be used to format documents outside the
- tree. Use \program{mkhowto} \longprogramopt{help}
- for a list of
- command line options.
-
- \program{mkhowto} can be used for both \code{howto} and
- \code{manual} class documents. It is usually a good idea to
- always use the latest version of this tool rather than a
- version from an older source release of Python.
-
- XXX Need more here.
- \end{description}
-
-
- \subsection{Working on Cygwin \label{cygwin}}
-
- Installing the required tools under Cygwin under Cygwin can be a
- little tedious, if only because many packages are more difficult
- to install under Cygwin.
-
- Using the Cygwin installer, make sure your Cygwin installation
- includes Perl, Python, and the \TeX{} packages. Perl and Python
- are located under \menuselection{Interpreters} in the installer
- The \TeX{} packages are located in the \menuselection{Text}
- section; installing the tetex-beta, texmf, texmf-base, and
- texmf-extra ensures that all the required packages are available.
- (There may be a more minimal set, but I've not spent time trying
- to minimize the installation.)
-
- The netpbm package is used by \LaTeX2HTML, and \emph{must} be
- installed before \LaTeX2HTML can be successfully installed, even
- though they will never be used for most Python documentation.
- References to download locations are located in the \ulink{netpbm
- README}{http://netpbm.sourceforge.net/README}. Install according
- to the instructions.
-
- \LaTeX2HTML can be installed from the source archive, but only
- after munging one of the files in the distribution. Edit the file
- \file{L2hos.pm} in the top level of the unpacked distribution;
- near the bottom of the file, change the text
- \code{\$\textasciicircum{}O} with the text \code{'unix'}. Proceed
- using this command to build and install the software:
-
-\begin{verbatim}
-% configure && make install
-\end{verbatim}
-
- You should now be able to build at least the HTML, PDF, and
- PostScript versions of the formatted documentation.
-
-
-\section{Future Directions \label{futures}}
-
- The history of the Python documentation is full of changes, most of
- which have been fairly small and evolutionary. There has been a
- great deal of discussion about making large changes in the markup
- languages and tools used to process the documentation. This section
- deals with the nature of the changes and what appears to be the most
- likely path of future development.
-
- \subsection{Structured Documentation \label{structured}}
-
- Most of the small changes to the \LaTeX{} markup have been made
- with an eye to divorcing the markup from the presentation, making
- both a bit more maintainable. Over the course of 1998, a large
- number of changes were made with exactly this in mind; previously,
- changes had been made but in a less systematic manner and with
- more concern for not needing to update the existing content. The
- result has been a highly structured and semantically loaded markup
- language implemented in \LaTeX. With almost no basic \TeX{} or
- \LaTeX{} markup in use, however, the markup syntax is about the
- only evidence of \LaTeX{} in the actual document sources.
-
- One side effect of this is that while we've been able to use
- standard ``engines'' for manipulating the documents, such as
- \LaTeX{} and \LaTeX2HTML, most of the actual transformations have
- been created specifically for Python. The \LaTeX{} document
- classes and \LaTeX2HTML support are both complete implementations
- of the specific markup designed for these documents.
-
- Combining highly customized markup with the somewhat esoteric
- systems used to process the documents leads us to ask some
- questions: Can we do this more easily? and, Can we do this
- better? After a great deal of discussion with the community, we
- have determined that actively pursuing modern structured
- documentation systems is worth some investment of time.
-
- There appear to be two real contenders in this arena: the Standard
- General Markup Language (SGML), and the Extensible Markup Language
- (XML). Both of these standards have advantages and disadvantages,
- and many advantages are shared.
-
- SGML offers advantages which may appeal most to authors,
- especially those using ordinary text editors. There are also
- additional abilities to define content models. A number of
- high-quality tools with demonstrated maturity are available, but
- most are not free; for those which are, portability issues remain
- a problem.
-
- The advantages of XML include the availability of a large number
- of evolving tools. Unfortunately, many of the associated
- standards are still evolving, and the tools will have to follow
- along. This means that developing a robust tool set that uses
- more than the basic XML 1.0 recommendation is not possible in the
- short term. The promised availability of a wide variety of
- high-quality tools which support some of the most important
- related standards is not immediate. Many tools are likely to be
- free, and the portability issues of those which are, are not
- expected to be significant.
-
- It turns out that converting to an XML or SGML system holds
- promise for translators as well; how much can be done to ease the
- burden on translators remains to be seen, and may have some impact
- on the schema and specific technologies used.
-
- XXX Eventual migration to XML.
-
- The documentation will be moved to XML in the future, and tools
- are being written which will convert the documentation from the
- current format to something close to a finished version, to the
- extent that the desired information is already present in the
- documentation. Some XSLT stylesheets have been started for
- presenting a preliminary XML version as HTML, but the results are
- fairly rough..
-
- The timeframe for the conversion is not clear since there doesn't
- seem to be much time available to work on this, but the appearant
- benefits are growing more substantial at a moderately rapid pace.
-
-
- \subsection{Discussion Forums \label{discussion}}
-
- Discussion of the future of the Python documentation and related
- topics takes place in the Documentation Special Interest Group, or
- ``Doc-SIG.'' Information on the group, including mailing list
- archives and subscription information, is available at
- \url{http://www.python.org/sigs/doc-sig/}. The SIG is open to all
- interested parties.
-
- Comments and bug reports on the standard documents should be sent
- to \email{python-docs@python.org}. This may include comments
- about formatting, content, grammatical and spelling errors, or
- this document. You can also send comments on this document
- directly to the author at \email{fdrake@acm.org}.
-
-\input{doc.ind}
-
-\end{document}
diff --git a/Doc/ext/.cvsignore b/Doc/ext/.cvsignore
deleted file mode 100644
index ea4fca3aac..0000000000
--- a/Doc/ext/.cvsignore
+++ /dev/null
@@ -1,3 +0,0 @@
-*.esis
-*.esis1
-*.xml
diff --git a/Doc/ext/building.tex b/Doc/ext/building.tex
deleted file mode 100644
index 42384c1bf0..0000000000
--- a/Doc/ext/building.tex
+++ /dev/null
@@ -1,143 +0,0 @@
-\chapter{Building C and \Cpp{} Extensions with distutils
- \label{building}}
-
-\sectionauthor{Martin v. L\"owis}{martin@v.loewis.de}
-
-Starting in Python 1.4, Python provides, on \UNIX{}, a special make
-file for building make files for building dynamically-linked
-extensions and custom interpreters. Starting with Python 2.0, this
-mechanism (known as related to Makefile.pre.in, and Setup files) is no
-longer supported. Building custom interpreters was rarely used, and
-extension modules can be built using distutils.
-
-Building an extension module using distutils requires that distutils
-is installed on the build machine, which is included in Python 2.x and
-available separately for Python 1.5. Since distutils also supports
-creation of binary packages, users don't necessarily need a compiler
-and distutils to install the extension.
-
-A distutils package contains a driver script, \file{setup.py}. This is
-a plain Python file, which, in the most simple case, could look like
-this:
-
-\begin{verbatim}
-from distutils.core import setup, Extension
-
-module1 = Extension('demo',
- sources = ['demo.c'])
-
-setup (name = 'PackageName',
- version = '1.0',
- description = 'This is a demo package',
- ext_modules = [module1])
-
-\end{verbatim}
-
-With this \file{setup.py}, and a file \file{demo.c}, running
-
-\begin{verbatim}
-python setup.py build
-\end{verbatim}
-
-will compile \file{demo.c}, and produce an extension module named
-\samp{demo} in the \file{build} directory. Depending on the system,
-the module file will end up in a subdirectory \file{build/lib.system},
-and may have a name like \file{demo.so} or \file{demo.pyd}.
-
-In the \file{setup.py}, all execution is performed by calling the
-\samp{setup} function. This takes a variable number of keyword
-arguments, of which the example above uses only a
-subset. Specifically, the example specifies meta-information to build
-packages, and it specifies the contents of the package. Normally, a
-package will contain of addition modules, like Python source modules,
-documentation, subpackages, etc. Please refer to the distutils
-documentation in \citetitle[../dist/dist.html]{Distributing Python
-Modules} to learn more about the features of distutils; this section
-explains building extension modules only.
-
-It is common to pre-compute arguments to \function{setup}, to better
-structure the driver script. In the example above,
-the\samp{ext_modules} argument to \function{setup} is a list of
-extension modules, each of which is an instance of the
-\class{Extension}. In the example, the instance defines an extension
-named \samp{demo} which is build by compiling a single source file,
-\file{demo.c}.
-
-In many cases, building an extension is more complex, since additional
-preprocessor defines and libraries may be needed. This is demonstrated
-in the example below.
-
-\begin{verbatim}
-from distutils.core import setup, Extension
-
-module1 = Extension('demo',
- define_macros = [('MAJOR_VERSION', '1'),
- ('MINOR_VERSION', '0')],
- include_dirs = ['/usr/local/include'],
- libraries = ['tcl83'],
- library_dirs = ['/usr/local/lib'],
- sources = ['demo.c'])
-
-setup (name = 'PackageName',
- version = '1.0',
- description = 'This is a demo package',
- author = 'Martin v. Loewis',
- author_email = 'martin@v.loewis.de',
- url = 'http://www.python.org/doc/current/ext/building.html',
- long_description = '''
-This is really just a demo package.
-''',
- ext_modules = [module1])
-
-\end{verbatim}
-
-In this example, \function{setup} is called with additional
-meta-information, which is recommended when distribution packages have
-to be built. For the extension itself, it specifies preprocessor
-defines, include directories, library directories, and libraries.
-Depending on the compiler, distutils passes this information in
-different ways to the compiler. For example, on \UNIX{}, this may
-result in the compilation commands
-
-\begin{verbatim}
-gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DMAJOR_VERSION=1 -DMINOR_VERSION=0 -I/usr/local/include -I/usr/local/include/python2.2 -c demo.c -o build/temp.linux-i686-2.2/demo.o
-
-gcc -shared build/temp.linux-i686-2.2/demo.o -L/usr/local/lib -ltcl83 -o build/lib.linux-i686-2.2/demo.so
-\end{verbatim}
-
-These lines are for demonstration purposes only; distutils users
-should trust that distutils gets the invocations right.
-
-\section{Distributing your extension modules
- \label{distributing}}
-
-When an extension has been successfully build, there are three ways to
-use it.
-
-End-users will typically want to install the module, they do so by
-running
-
-\begin{verbatim}
-python setup.py install
-\end{verbatim}
-
-Module maintainers should produce source packages; to do so, they run
-
-\begin{verbatim}
-python setup.py sdist
-\end{verbatim}
-
-In some cases, additional files need to be included in a source
-distribution; this is done through a \file{MANIFEST.in} file; see the
-distutils documentation for details.
-
-If the source distribution has been build successfully, maintainers
-can also create binary distributions. Depending on the platform, one
-of the following commands can be used to do so.
-
-\begin{verbatim}
-python setup.py bdist_wininst
-python setup.py bdist_rpm
-python setup.py bdist_dumb
-\end{verbatim}
-
diff --git a/Doc/ext/cycle-gc.c b/Doc/ext/cycle-gc.c
deleted file mode 100644
index c3a0caa5b7..0000000000
--- a/Doc/ext/cycle-gc.c
+++ /dev/null
@@ -1,79 +0,0 @@
-#include "Python.h"
-
-typedef struct {
- PyObject_HEAD
- PyObject *container;
-} MyObject;
-
-static int
-my_traverse(MyObject *self, visitproc visit, void *arg)
-{
- if (self->container != NULL)
- return visit(self->container, arg);
- else
- return 0;
-}
-
-static int
-my_clear(MyObject *self)
-{
- Py_XDECREF(self->container);
- self->container = NULL;
-
- return 0;
-}
-
-static void
-my_dealloc(MyObject *self)
-{
- PyObject_GC_UnTrack((PyObject *) self);
- Py_XDECREF(self->container);
- PyObject_GC_Del(self);
-}
-
-static PyTypeObject
-MyObject_Type = {
- PyObject_HEAD_INIT(NULL)
- 0,
- "MyObject",
- sizeof(MyObject),
- 0,
- (destructor)my_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
- 0, /* tp_doc */
- (traverseproc)my_traverse, /* tp_traverse */
- (inquiry)my_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
-};
-
-/* This constructor should be made accessible from Python. */
-static PyObject *
-new_object(PyObject *unused, PyObject *args)
-{
- PyObject *container = NULL;
- MyObject *result = NULL;
-
- if (PyArg_ParseTuple(args, "|O:new_object", &container)) {
- result = PyObject_GC_New(MyObject, &MyObject_Type);
- if (result != NULL) {
- result->container = container;
- PyObject_GC_Track(result);
- }
- }
- return (PyObject *) result;
-}
diff --git a/Doc/ext/embedding.tex b/Doc/ext/embedding.tex
deleted file mode 100644
index 3c48c9d6f6..0000000000
--- a/Doc/ext/embedding.tex
+++ /dev/null
@@ -1,316 +0,0 @@
-\chapter{Embedding Python in Another Application
- \label{embedding}}
-
-The previous chapters discussed how to extend Python, that is, how to
-extend the functionality of Python by attaching a library of C
-functions to it. It is also possible to do it the other way around:
-enrich your C/\Cpp{} application by embedding Python in it. Embedding
-provides your application with the ability to implement some of the
-functionality of your application in Python rather than C or \Cpp.
-This can be used for many purposes; one example would be to allow
-users to tailor the application to their needs by writing some scripts
-in Python. You can also use it yourself if some of the functionality
-can be written in Python more easily.
-
-Embedding Python is similar to extending it, but not quite. The
-difference is that when you extend Python, the main program of the
-application is still the Python interpreter, while if you embed
-Python, the main program may have nothing to do with Python ---
-instead, some parts of the application occasionally call the Python
-interpreter to run some Python code.
-
-So if you are embedding Python, you are providing your own main
-program. One of the things this main program has to do is initialize
-the Python interpreter. At the very least, you have to call the
-function \cfunction{Py_Initialize()} (on Mac OS, call
-\cfunction{PyMac_Initialize()} instead). There are optional calls to
-pass command line arguments to Python. Then later you can call the
-interpreter from any part of the application.
-
-There are several different ways to call the interpreter: you can pass
-a string containing Python statements to
-\cfunction{PyRun_SimpleString()}, or you can pass a stdio file pointer
-and a file name (for identification in error messages only) to
-\cfunction{PyRun_SimpleFile()}. You can also call the lower-level
-operations described in the previous chapters to construct and use
-Python objects.
-
-A simple demo of embedding Python can be found in the directory
-\file{Demo/embed/} of the source distribution.
-
-
-\begin{seealso}
- \seetitle[../api/api.html]{Python/C API Reference Manual}{The
- details of Python's C interface are given in this manual.
- A great deal of necessary information can be found here.}
-\end{seealso}
-
-
-\section{Very High Level Embedding
- \label{high-level-embedding}}
-
-The simplest form of embedding Python is the use of the very
-high level interface. This interface is intended to execute a
-Python script without needing to interact with the application
-directly. This can for example be used to perform some operation
-on a file.
-
-\begin{verbatim}
-#include
-
-int
-main(int argc, char *argv[])
-{
- Py_Initialize();
- PyRun_SimpleString("from time import time,ctime\n"
- "print 'Today is',ctime(time())\n");
- Py_Finalize();
- return 0;
-}
-\end{verbatim}
-
-The above code first initializes the Python interpreter with
-\cfunction{Py_Initialize()}, followed by the execution of a hard-coded
-Python script that print the date and time. Afterwards, the
-\cfunction{Py_Finalize()} call shuts the interpreter down, followed by
-the end of the program. In a real program, you may want to get the
-Python script from another source, perhaps a text-editor routine, a
-file, or a database. Getting the Python code from a file can better
-be done by using the \cfunction{PyRun_SimpleFile()} function, which
-saves you the trouble of allocating memory space and loading the file
-contents.
-
-
-\section{Beyond Very High Level Embedding: An overview
- \label{lower-level-embedding}}
-
-The high level interface gives you the ability to execute
-arbitrary pieces of Python code from your application, but
-exchanging data values is quite cumbersome to say the least. If
-you want that, you should use lower level calls. At the cost of
-having to write more C code, you can achieve almost anything.
-
-It should be noted that extending Python and embedding Python
-is quite the same activity, despite the different intent. Most
-topics discussed in the previous chapters are still valid. To
-show this, consider what the extension code from Python to C
-really does:
-
-\begin{enumerate}
- \item Convert data values from Python to C,
- \item Perform a function call to a C routine using the
- converted values, and
- \item Convert the data values from the call from C to Python.
-\end{enumerate}
-
-When embedding Python, the interface code does:
-
-\begin{enumerate}
- \item Convert data values from C to Python,
- \item Perform a function call to a Python interface routine
- using the converted values, and
- \item Convert the data values from the call from Python to C.
-\end{enumerate}
-
-As you can see, the data conversion steps are simply swapped to
-accomodate the different direction of the cross-language transfer.
-The only difference is the routine that you call between both
-data conversions. When extending, you call a C routine, when
-embedding, you call a Python routine.
-
-This chapter will not discuss how to convert data from Python
-to C and vice versa. Also, proper use of references and dealing
-with errors is assumed to be understood. Since these aspects do not
-differ from extending the interpreter, you can refer to earlier
-chapters for the required information.
-
-
-\section{Pure Embedding
- \label{pure-embedding}}
-
-The first program aims to execute a function in a Python
-script. Like in the section about the very high level interface,
-the Python interpreter does not directly interact with the
-application (but that will change in th next section).
-
-The code to run a function defined in a Python script is:
-
-\verbatiminput{run-func.c}
-
-This code loads a Python script using \code{argv[1]}, and calls the
-function named in \code{argv[2]}. Its integer arguments are the other
-values of the \code{argv} array. If you compile and link this
-program (let's call the finished executable \program{call}), and use
-it to execute a Python script, such as:
-
-\begin{verbatim}
-def multiply(a,b):
- print "Will compute", a, "times", b
- c = 0
- for i in range(0, a):
- c = c + b
- return c
-\end{verbatim}
-
-then the result should be:
-
-\begin{verbatim}
-$ call multiply multiply 3 2
-Will compute 3 times 2
-Result of call: 6
-\end{verbatim} % $
-
-Although the program is quite large for its functionality, most of the
-code is for data conversion between Python and C, and for error
-reporting. The interesting part with respect to embedding Python
-starts with
-
-\begin{verbatim}
- Py_Initialize();
- pName = PyString_FromString(argv[1]);
- /* Error checking of pName left out */
- pModule = PyImport_Import(pName);
-\end{verbatim}
-
-After initializing the interpreter, the script is loaded using
-\cfunction{PyImport_Import()}. This routine needs a Python string
-as its argument, which is constructed using the
-\cfunction{PyString_FromString()} data conversion routine.
-
-\begin{verbatim}
- pFunc = PyObject_GetAttrString(pModule, argv[2]);
- /* pFunc is a new reference */
-
- if (pFunc && PyCallable_Check(pFunc)) {
- ...
- }
- Py_XDECREF(pFunc);
-\end{verbatim}
-
-Once the script is loaded, the name we're looking for is retrieved
-using \cfunction{PyObject_GetAttrString()}. If the name exists, and
-the object returned is callable, you can safely assume that it is a
-function. The program then proceeds by constructing a tuple of
-arguments as normal. The call to the Python function is then made
-with:
-
-\begin{verbatim}
- pValue = PyObject_CallObject(pFunc, pArgs);
-\end{verbatim}
-
-Upon return of the function, \code{pValue} is either \NULL{} or it
-contains a reference to the return value of the function. Be sure to
-release the reference after examining the value.
-
-
-\section{Extending Embedded Python
- \label{extending-with-embedding}}
-
-Until now, the embedded Python interpreter had no access to
-functionality from the application itself. The Python API allows this
-by extending the embedded interpreter. That is, the embedded
-interpreter gets extended with routines provided by the application.
-While it sounds complex, it is not so bad. Simply forget for a while
-that the application starts the Python interpreter. Instead, consider
-the application to be a set of subroutines, and write some glue code
-that gives Python access to those routines, just like you would write
-a normal Python extension. For example:
-
-\begin{verbatim}
-static int numargs=0;
-
-/* Return the number of arguments of the application command line */
-static PyObject*
-emb_numargs(PyObject *self, PyObject *args)
-{
- if(!PyArg_ParseTuple(args, ":numargs"))
- return NULL;
- return Py_BuildValue("i", numargs);
-}
-
-static PyMethodDef EmbMethods[] = {
- {"numargs", emb_numargs, METH_VARARGS,
- "Return the number of arguments received by the process."},
- {NULL, NULL, 0, NULL}
-};
-\end{verbatim}
-
-Insert the above code just above the \cfunction{main()} function.
-Also, insert the following two statements directly after
-\cfunction{Py_Initialize()}:
-
-\begin{verbatim}
- numargs = argc;
- Py_InitModule("emb", EmbMethods);
-\end{verbatim}
-
-These two lines initialize the \code{numargs} variable, and make the
-\function{emb.numargs()} function accessible to the embedded Python
-interpreter. With these extensions, the Python script can do things
-like
-
-\begin{verbatim}
-import emb
-print "Number of arguments", emb.numargs()
-\end{verbatim}
-
-In a real application, the methods will expose an API of the
-application to Python.
-
-
-%\section{For the future}
-%
-%You don't happen to have a nice library to get textual
-%equivalents of numeric values do you :-) ?
-%Callbacks here ? (I may be using information from that section
-%?!)
-%threads
-%code examples do not really behave well if errors happen
-% (what to watch out for)
-
-
-\section{Embedding Python in \Cpp
- \label{embeddingInCplusplus}}
-
-It is also possible to embed Python in a \Cpp{} program; precisely how this
-is done will depend on the details of the \Cpp{} system used; in general you
-will need to write the main program in \Cpp, and use the \Cpp{} compiler
-to compile and link your program. There is no need to recompile Python
-itself using \Cpp.
-
-
-\section{Linking Requirements
- \label{link-reqs}}
-
-While the \program{configure} script shipped with the Python sources
-will correctly build Python to export the symbols needed by
-dynamically linked extensions, this is not automatically inherited by
-applications which embed the Python library statically, at least on
-\UNIX. This is an issue when the application is linked to the static
-runtime library (\file{libpython.a}) and needs to load dynamic
-extensions (implemented as \file{.so} files).
-
-The problem is that some entry points are defined by the Python
-runtime solely for extension modules to use. If the embedding
-application does not use any of these entry points, some linkers will
-not include those entries in the symbol table of the finished
-executable. Some additional options are needed to inform the linker
-not to remove these symbols.
-
-Determining the right options to use for any given platform can be
-quite difficult, but fortunately the Python configuration already has
-those values. To retrieve them from an installed Python interpreter,
-start an interactive interpreter and have a short session like this:
-
-\begin{verbatim}
->>> import distutils.sysconfig
->>> distutils.sysconfig.get_config_var('LINKFORSHARED')
-'-Xlinker -export-dynamic'
-\end{verbatim}
-\refstmodindex{distutils.sysconfig}
-
-The contents of the string presented will be the options that should
-be used. If the string is empty, there's no need to add any
-additional options. The \constant{LINKFORSHARED} definition
-corresponds to the variable of the same name in Python's top-level
-\file{Makefile}.
diff --git a/Doc/ext/ext.tex b/Doc/ext/ext.tex
deleted file mode 100644
index b4130d13a7..0000000000
--- a/Doc/ext/ext.tex
+++ /dev/null
@@ -1,67 +0,0 @@
-\documentclass{manual}
-
-% XXX PM explain how to add new types to Python
-
-\title{Extending and Embedding the Python Interpreter}
-
-\input{boilerplate}
-
-% Tell \index to actually write the .idx file
-\makeindex
-
-\begin{document}
-
-\maketitle
-
-\ifhtml
-\chapter*{Front Matter\label{front}}
-\fi
-
-\input{copyright}
-
-
-\begin{abstract}
-
-\noindent
-Python is an interpreted, object-oriented programming language. This
-document describes how to write modules in C or \Cpp{} to extend the
-Python interpreter with new modules. Those modules can define new
-functions but also new object types and their methods. The document
-also describes how to embed the Python interpreter in another
-application, for use as an extension language. Finally, it shows how
-to compile and link extension modules so that they can be loaded
-dynamically (at run time) into the interpreter, if the underlying
-operating system supports this feature.
-
-This document assumes basic knowledge about Python. For an informal
-introduction to the language, see the
-\citetitle[../tut/tut.html]{Python Tutorial}. The
-\citetitle[../ref/ref.html]{Python Reference Manual} gives a more
-formal definition of the language. The
-\citetitle[../lib/lib.html]{Python Library Reference} documents the
-existing object types, functions and modules (both built-in and
-written in Python) that give the language its wide application range.
-
-For a detailed description of the whole Python/C API, see the separate
-\citetitle[../api/api.html]{Python/C API Reference Manual}.
-
-\end{abstract}
-
-\tableofcontents
-
-
-\input{extending}
-\input{newtypes}
-\input{building}
-\input{windows}
-\input{embedding}
-
-
-\appendix
-\chapter{Reporting Bugs}
-\input{reportingbugs}
-
-\chapter{History and License}
-\input{license}
-
-\end{document}
diff --git a/Doc/ext/extending.tex b/Doc/ext/extending.tex
deleted file mode 100644
index 0f38e96f10..0000000000
--- a/Doc/ext/extending.tex
+++ /dev/null
@@ -1,1380 +0,0 @@
-\chapter{Extending Python with C or \Cpp \label{intro}}
-
-
-It is quite easy to add new built-in modules to Python, if you know
-how to program in C. Such \dfn{extension modules} can do two things
-that can't be done directly in Python: they can implement new built-in
-object types, and they can call C library functions and system calls.
-
-To support extensions, the Python API (Application Programmers
-Interface) defines a set of functions, macros and variables that
-provide access to most aspects of the Python run-time system. The
-Python API is incorporated in a C source file by including the header
-\code{"Python.h"}.
-
-The compilation of an extension module depends on its intended use as
-well as on your system setup; details are given in later chapters.
-
-
-\section{A Simple Example
- \label{simpleExample}}
-
-Let's create an extension module called \samp{spam} (the favorite food
-of Monty Python fans...) and let's say we want to create a Python
-interface to the C library function \cfunction{system()}.\footnote{An
-interface for this function already exists in the standard module
-\module{os} --- it was chosen as a simple and straightfoward example.}
-This function takes a null-terminated character string as argument and
-returns an integer. We want this function to be callable from Python
-as follows:
-
-\begin{verbatim}
->>> import spam
->>> status = spam.system("ls -l")
-\end{verbatim}
-
-Begin by creating a file \file{spammodule.c}. (Historically, if a
-module is called \samp{spam}, the C file containing its implementation
-is called \file{spammodule.c}; if the module name is very long, like
-\samp{spammify}, the module name can be just \file{spammify.c}.)
-
-The first line of our file can be:
-
-\begin{verbatim}
-#include
-\end{verbatim}
-
-which pulls in the Python API (you can add a comment describing the
-purpose of the module and a copyright notice if you like).
-Since Python may define some pre-processor definitions which affect
-the standard headers on some systems, you must include \file{Python.h}
-before any standard headers are included.
-
-All user-visible symbols defined by \file{Python.h} have a prefix of
-\samp{Py} or \samp{PY}, except those defined in standard header files.
-For convenience, and since they are used extensively by the Python
-interpreter, \code{"Python.h"} includes a few standard header files:
-\code{}, \code{}, \code{}, and
-\code{}. If the latter header file does not exist on your
-system, it declares the functions \cfunction{malloc()},
-\cfunction{free()} and \cfunction{realloc()} directly.
-
-The next thing we add to our module file is the C function that will
-be called when the Python expression \samp{spam.system(\var{string})}
-is evaluated (we'll see shortly how it ends up being called):
-
-\begin{verbatim}
-static PyObject *
-spam_system(PyObject *self, PyObject *args)
-{
- char *command;
- int sts;
-
- if (!PyArg_ParseTuple(args, "s", &command))
- return NULL;
- sts = system(command);
- return Py_BuildValue("i", sts);
-}
-\end{verbatim}
-
-There is a straightforward translation from the argument list in
-Python (for example, the single expression \code{"ls -l"}) to the
-arguments passed to the C function. The C function always has two
-arguments, conventionally named \var{self} and \var{args}.
-
-The \var{self} argument is only used when the C function implements a
-built-in method, not a function. In the example, \var{self} will
-always be a \NULL{} pointer, since we are defining a function, not a
-method. (This is done so that the interpreter doesn't have to
-understand two different types of C functions.)
-
-The \var{args} argument will be a pointer to a Python tuple object
-containing the arguments. Each item of the tuple corresponds to an
-argument in the call's argument list. The arguments are Python
-objects --- in order to do anything with them in our C function we have
-to convert them to C values. The function \cfunction{PyArg_ParseTuple()}
-in the Python API checks the argument types and converts them to C
-values. It uses a template string to determine the required types of
-the arguments as well as the types of the C variables into which to
-store the converted values. More about this later.
-
-\cfunction{PyArg_ParseTuple()} returns true (nonzero) if all arguments have
-the right type and its components have been stored in the variables
-whose addresses are passed. It returns false (zero) if an invalid
-argument list was passed. In the latter case it also raises an
-appropriate exception so the calling function can return
-\NULL{} immediately (as we saw in the example).
-
-
-\section{Intermezzo: Errors and Exceptions
- \label{errors}}
-
-An important convention throughout the Python interpreter is the
-following: when a function fails, it should set an exception condition
-and return an error value (usually a \NULL{} pointer). Exceptions
-are stored in a static global variable inside the interpreter; if this
-variable is \NULL{} no exception has occurred. A second global
-variable stores the ``associated value'' of the exception (the second
-argument to \keyword{raise}). A third variable contains the stack
-traceback in case the error originated in Python code. These three
-variables are the C equivalents of the Python variables
-\code{sys.exc_type}, \code{sys.exc_value} and \code{sys.exc_traceback} (see
-the section on module \module{sys} in the
-\citetitle[../lib/lib.html]{Python Library Reference}). It is
-important to know about them to understand how errors are passed
-around.
-
-The Python API defines a number of functions to set various types of
-exceptions.
-
-The most common one is \cfunction{PyErr_SetString()}. Its arguments
-are an exception object and a C string. The exception object is
-usually a predefined object like \cdata{PyExc_ZeroDivisionError}. The
-C string indicates the cause of the error and is converted to a
-Python string object and stored as the ``associated value'' of the
-exception.
-
-Another useful function is \cfunction{PyErr_SetFromErrno()}, which only
-takes an exception argument and constructs the associated value by
-inspection of the global variable \cdata{errno}. The most
-general function is \cfunction{PyErr_SetObject()}, which takes two object
-arguments, the exception and its associated value. You don't need to
-\cfunction{Py_INCREF()} the objects passed to any of these functions.
-
-You can test non-destructively whether an exception has been set with
-\cfunction{PyErr_Occurred()}. This returns the current exception object,
-or \NULL{} if no exception has occurred. You normally don't need
-to call \cfunction{PyErr_Occurred()} to see whether an error occurred in a
-function call, since you should be able to tell from the return value.
-
-When a function \var{f} that calls another function \var{g} detects
-that the latter fails, \var{f} should itself return an error value
-(usually \NULL{} or \code{-1}). It should \emph{not} call one of the
-\cfunction{PyErr_*()} functions --- one has already been called by \var{g}.
-\var{f}'s caller is then supposed to also return an error indication
-to \emph{its} caller, again \emph{without} calling \cfunction{PyErr_*()},
-and so on --- the most detailed cause of the error was already
-reported by the function that first detected it. Once the error
-reaches the Python interpreter's main loop, this aborts the currently
-executing Python code and tries to find an exception handler specified
-by the Python programmer.
-
-(There are situations where a module can actually give a more detailed
-error message by calling another \cfunction{PyErr_*()} function, and in
-such cases it is fine to do so. As a general rule, however, this is
-not necessary, and can cause information about the cause of the error
-to be lost: most operations can fail for a variety of reasons.)
-
-To ignore an exception set by a function call that failed, the exception
-condition must be cleared explicitly by calling \cfunction{PyErr_Clear()}.
-The only time C code should call \cfunction{PyErr_Clear()} is if it doesn't
-want to pass the error on to the interpreter but wants to handle it
-completely by itself (possibly by trying something else, or pretending
-nothing went wrong).
-
-Every failing \cfunction{malloc()} call must be turned into an
-exception --- the direct caller of \cfunction{malloc()} (or
-\cfunction{realloc()}) must call \cfunction{PyErr_NoMemory()} and
-return a failure indicator itself. All the object-creating functions
-(for example, \cfunction{PyInt_FromLong()}) already do this, so this
-note is only relevant to those who call \cfunction{malloc()} directly.
-
-Also note that, with the important exception of
-\cfunction{PyArg_ParseTuple()} and friends, functions that return an
-integer status usually return a positive value or zero for success and
-\code{-1} for failure, like \UNIX{} system calls.
-
-Finally, be careful to clean up garbage (by making
-\cfunction{Py_XDECREF()} or \cfunction{Py_DECREF()} calls for objects
-you have already created) when you return an error indicator!
-
-The choice of which exception to raise is entirely yours. There are
-predeclared C objects corresponding to all built-in Python exceptions,
-such as \cdata{PyExc_ZeroDivisionError}, which you can use directly.
-Of course, you should choose exceptions wisely --- don't use
-\cdata{PyExc_TypeError} to mean that a file couldn't be opened (that
-should probably be \cdata{PyExc_IOError}). If something's wrong with
-the argument list, the \cfunction{PyArg_ParseTuple()} function usually
-raises \cdata{PyExc_TypeError}. If you have an argument whose value
-must be in a particular range or must satisfy other conditions,
-\cdata{PyExc_ValueError} is appropriate.
-
-You can also define a new exception that is unique to your module.
-For this, you usually declare a static object variable at the
-beginning of your file:
-
-\begin{verbatim}
-static PyObject *SpamError;
-\end{verbatim}
-
-and initialize it in your module's initialization function
-(\cfunction{initspam()}) with an exception object (leaving out
-the error checking for now):
-
-\begin{verbatim}
-PyMODINIT_FUNC
-initspam(void)
-{
- PyObject *m;
-
- m = Py_InitModule("spam", SpamMethods);
-
- SpamError = PyErr_NewException("spam.error", NULL, NULL);
- Py_INCREF(SpamError);
- PyModule_AddObject(m, "error", SpamError);
-}
-\end{verbatim}
-
-Note that the Python name for the exception object is
-\exception{spam.error}. The \cfunction{PyErr_NewException()} function
-may create a class with the base class being \exception{Exception}
-(unless another class is passed in instead of \NULL), described in the
-\citetitle[../lib/lib.html]{Python Library Reference} under ``Built-in
-Exceptions.''
-
-Note also that the \cdata{SpamError} variable retains a reference to
-the newly created exception class; this is intentional! Since the
-exception could be removed from the module by external code, an owned
-reference to the class is needed to ensure that it will not be
-discarded, causing \cdata{SpamError} to become a dangling pointer.
-Should it become a dangling pointer, C code which raises the exception
-could cause a core dump or other unintended side effects.
-
-We discuss the use of PyMODINIT_FUNC later in this sample.
-
-\section{Back to the Example
- \label{backToExample}}
-
-Going back to our example function, you should now be able to
-understand this statement:
-
-\begin{verbatim}
- if (!PyArg_ParseTuple(args, "s", &command))
- return NULL;
-\end{verbatim}
-
-It returns \NULL{} (the error indicator for functions returning
-object pointers) if an error is detected in the argument list, relying
-on the exception set by \cfunction{PyArg_ParseTuple()}. Otherwise the
-string value of the argument has been copied to the local variable
-\cdata{command}. This is a pointer assignment and you are not supposed
-to modify the string to which it points (so in Standard C, the variable
-\cdata{command} should properly be declared as \samp{const char
-*command}).
-
-The next statement is a call to the \UNIX{} function
-\cfunction{system()}, passing it the string we just got from
-\cfunction{PyArg_ParseTuple()}:
-
-\begin{verbatim}
- sts = system(command);
-\end{verbatim}
-
-Our \function{spam.system()} function must return the value of
-\cdata{sts} as a Python object. This is done using the function
-\cfunction{Py_BuildValue()}, which is something like the inverse of
-\cfunction{PyArg_ParseTuple()}: it takes a format string and an
-arbitrary number of C values, and returns a new Python object.
-More info on \cfunction{Py_BuildValue()} is given later.
-
-\begin{verbatim}
- return Py_BuildValue("i", sts);
-\end{verbatim}
-
-In this case, it will return an integer object. (Yes, even integers
-are objects on the heap in Python!)
-
-If you have a C function that returns no useful argument (a function
-returning \ctype{void}), the corresponding Python function must return
-\code{None}. You need this idiom to do so:
-
-\begin{verbatim}
- Py_INCREF(Py_None);
- return Py_None;
-\end{verbatim}
-
-\cdata{Py_None} is the C name for the special Python object
-\code{None}. It is a genuine Python object rather than a \NULL{}
-pointer, which means ``error'' in most contexts, as we have seen.
-
-
-\section{The Module's Method Table and Initialization Function
- \label{methodTable}}
-
-I promised to show how \cfunction{spam_system()} is called from Python
-programs. First, we need to list its name and address in a ``method
-table'':
-
-\begin{verbatim}
-static PyMethodDef SpamMethods[] = {
- ...
- {"system", spam_system, METH_VARARGS,
- "Execute a shell command."},
- ...
- {NULL, NULL, 0, NULL} /* Sentinel */
-};
-\end{verbatim}
-
-Note the third entry (\samp{METH_VARARGS}). This is a flag telling
-the interpreter the calling convention to be used for the C
-function. It should normally always be \samp{METH_VARARGS} or
-\samp{METH_VARARGS | METH_KEYWORDS}; a value of \code{0} means that an
-obsolete variant of \cfunction{PyArg_ParseTuple()} is used.
-
-When using only \samp{METH_VARARGS}, the function should expect
-the Python-level parameters to be passed in as a tuple acceptable for
-parsing via \cfunction{PyArg_ParseTuple()}; more information on this
-function is provided below.
-
-The \constant{METH_KEYWORDS} bit may be set in the third field if
-keyword arguments should be passed to the function. In this case, the
-C function should accept a third \samp{PyObject *} parameter which
-will be a dictionary of keywords. Use
-\cfunction{PyArg_ParseTupleAndKeywords()} to parse the arguments to
-such a function.
-
-The method table must be passed to the interpreter in the module's
-initialization function. The initialization function must be named
-\cfunction{init\var{name}()}, where \var{name} is the name of the
-module, and should be the only non-\keyword{static} item defined in
-the module file:
-
-\begin{verbatim}
-PyMODINIT_FUNC
-initspam(void)
-{
- (void) Py_InitModule("spam", SpamMethods);
-}
-\end{verbatim}
-
-Note that PyMODINIT_FUNC declares the function as \code{void} return type,
-declares any special linkage declarations required by the platform, and for
-\Cpp declares the function as \code{extern "C"}.
-
-When the Python program imports module \module{spam} for the first
-time, \cfunction{initspam()} is called. (See below for comments about
-embedding Python.) It calls
-\cfunction{Py_InitModule()}, which creates a ``module object'' (which
-is inserted in the dictionary \code{sys.modules} under the key
-\code{"spam"}), and inserts built-in function objects into the newly
-created module based upon the table (an array of \ctype{PyMethodDef}
-structures) that was passed as its second argument.
-\cfunction{Py_InitModule()} returns a pointer to the module object
-that it creates (which is unused here). It aborts with a fatal error
-if the module could not be initialized satisfactorily, so the caller
-doesn't need to check for errors.
-
-When embedding Python, the \cfunction{initspam()} function is not
-called automatically unless there's an entry in the
-\cdata{_PyImport_Inittab} table. The easiest way to handle this is to
-statically initialize your statically-linked modules by directly
-calling \cfunction{initspam()} after the call to
-\cfunction{Py_Initialize()} or \cfunction{PyMac_Initialize()}:
-
-\begin{verbatim}
-int
-main(int argc, char *argv[])
-{
- /* Pass argv[0] to the Python interpreter */
- Py_SetProgramName(argv[0]);
-
- /* Initialize the Python interpreter. Required. */
- Py_Initialize();
-
- /* Add a static module */
- initspam();
-\end{verbatim}
-
-An example may be found in the file \file{Demo/embed/demo.c} in the
-Python source distribution.
-
-\note{Removing entries from \code{sys.modules} or importing
-compiled modules into multiple interpreters within a process (or
-following a \cfunction{fork()} without an intervening
-\cfunction{exec()}) can create problems for some extension modules.
-Extension module authors should exercise caution when initializing
-internal data structures.
-Note also that the \function{reload()} function can be used with
-extension modules, and will call the module initialization function
-(\cfunction{initspam()} in the example), but will not load the module
-again if it was loaded from a dynamically loadable object file
-(\file{.so} on \UNIX, \file{.dll} on Windows).}
-
-A more substantial example module is included in the Python source
-distribution as \file{Modules/xxmodule.c}. This file may be used as a
-template or simply read as an example. The \program{modulator.py}
-script included in the source distribution or Windows install provides
-a simple graphical user interface for declaring the functions and
-objects which a module should implement, and can generate a template
-which can be filled in. The script lives in the
-\file{Tools/modulator/} directory; see the \file{README} file there
-for more information.
-
-
-\section{Compilation and Linkage
- \label{compilation}}
-
-There are two more things to do before you can use your new extension:
-compiling and linking it with the Python system. If you use dynamic
-loading, the details may depend on the style of dynamic loading your
-system uses; see the chapters about building extension modules
-(chapter \ref{building}) and additional information that pertains only
-to building on Windows (chapter \ref{building-on-windows}) for more
-information about this.
-% XXX Add information about Mac OS
-
-If you can't use dynamic loading, or if you want to make your module a
-permanent part of the Python interpreter, you will have to change the
-configuration setup and rebuild the interpreter. Luckily, this is
-very simple on \UNIX: just place your file (\file{spammodule.c} for
-example) in the \file{Modules/} directory of an unpacked source
-distribution, add a line to the file \file{Modules/Setup.local}
-describing your file:
-
-\begin{verbatim}
-spam spammodule.o
-\end{verbatim}
-
-and rebuild the interpreter by running \program{make} in the toplevel
-directory. You can also run \program{make} in the \file{Modules/}
-subdirectory, but then you must first rebuild \file{Makefile}
-there by running `\program{make} Makefile'. (This is necessary each
-time you change the \file{Setup} file.)
-
-If your module requires additional libraries to link with, these can
-be listed on the line in the configuration file as well, for instance:
-
-\begin{verbatim}
-spam spammodule.o -lX11
-\end{verbatim}
-
-\section{Calling Python Functions from C
- \label{callingPython}}
-
-So far we have concentrated on making C functions callable from
-Python. The reverse is also useful: calling Python functions from C.
-This is especially the case for libraries that support so-called
-``callback'' functions. If a C interface makes use of callbacks, the
-equivalent Python often needs to provide a callback mechanism to the
-Python programmer; the implementation will require calling the Python
-callback functions from a C callback. Other uses are also imaginable.
-
-Fortunately, the Python interpreter is easily called recursively, and
-there is a standard interface to call a Python function. (I won't
-dwell on how to call the Python parser with a particular string as
-input --- if you're interested, have a look at the implementation of
-the \programopt{-c} command line option in \file{Python/pythonmain.c}
-from the Python source code.)
-
-Calling a Python function is easy. First, the Python program must
-somehow pass you the Python function object. You should provide a
-function (or some other interface) to do this. When this function is
-called, save a pointer to the Python function object (be careful to
-\cfunction{Py_INCREF()} it!) in a global variable --- or wherever you
-see fit. For example, the following function might be part of a module
-definition:
-
-\begin{verbatim}
-static PyObject *my_callback = NULL;
-
-static PyObject *
-my_set_callback(PyObject *dummy, PyObject *args)
-{
- PyObject *result = NULL;
- PyObject *temp;
-
- if (PyArg_ParseTuple(args, "O:set_callback", &temp)) {
- if (!PyCallable_Check(temp)) {
- PyErr_SetString(PyExc_TypeError, "parameter must be callable");
- return NULL;
- }
- Py_XINCREF(temp); /* Add a reference to new callback */
- Py_XDECREF(my_callback); /* Dispose of previous callback */
- my_callback = temp; /* Remember new callback */
- /* Boilerplate to return "None" */
- Py_INCREF(Py_None);
- result = Py_None;
- }
- return result;
-}
-\end{verbatim}
-
-This function must be registered with the interpreter using the
-\constant{METH_VARARGS} flag; this is described in section
-\ref{methodTable}, ``The Module's Method Table and Initialization
-Function.'' The \cfunction{PyArg_ParseTuple()} function and its
-arguments are documented in section~\ref{parseTuple}, ``Extracting
-Parameters in Extension Functions.''
-
-The macros \cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()}
-increment/decrement the reference count of an object and are safe in
-the presence of \NULL{} pointers (but note that \var{temp} will not be
-\NULL{} in this context). More info on them in
-section~\ref{refcounts}, ``Reference Counts.''
-
-Later, when it is time to call the function, you call the C function
-\cfunction{PyEval_CallObject()}.\ttindex{PyEval_CallObject()} This
-function has two arguments, both pointers to arbitrary Python objects:
-the Python function, and the argument list. The argument list must
-always be a tuple object, whose length is the number of arguments. To
-call the Python function with no arguments, pass an empty tuple; to
-call it with one argument, pass a singleton tuple.
-\cfunction{Py_BuildValue()} returns a tuple when its format string
-consists of zero or more format codes between parentheses. For
-example:
-
-\begin{verbatim}
- int arg;
- PyObject *arglist;
- PyObject *result;
- ...
- arg = 123;
- ...
- /* Time to call the callback */
- arglist = Py_BuildValue("(i)", arg);
- result = PyEval_CallObject(my_callback, arglist);
- Py_DECREF(arglist);
-\end{verbatim}
-
-\cfunction{PyEval_CallObject()} returns a Python object pointer: this is
-the return value of the Python function. \cfunction{PyEval_CallObject()} is
-``reference-count-neutral'' with respect to its arguments. In the
-example a new tuple was created to serve as the argument list, which
-is \cfunction{Py_DECREF()}-ed immediately after the call.
-
-The return value of \cfunction{PyEval_CallObject()} is ``new'': either it
-is a brand new object, or it is an existing object whose reference
-count has been incremented. So, unless you want to save it in a
-global variable, you should somehow \cfunction{Py_DECREF()} the result,
-even (especially!) if you are not interested in its value.
-
-Before you do this, however, it is important to check that the return
-value isn't \NULL. If it is, the Python function terminated by
-raising an exception. If the C code that called
-\cfunction{PyEval_CallObject()} is called from Python, it should now
-return an error indication to its Python caller, so the interpreter
-can print a stack trace, or the calling Python code can handle the
-exception. If this is not possible or desirable, the exception should
-be cleared by calling \cfunction{PyErr_Clear()}. For example:
-
-\begin{verbatim}
- if (result == NULL)
- return NULL; /* Pass error back */
- ...use result...
- Py_DECREF(result);
-\end{verbatim}
-
-Depending on the desired interface to the Python callback function,
-you may also have to provide an argument list to
-\cfunction{PyEval_CallObject()}. In some cases the argument list is
-also provided by the Python program, through the same interface that
-specified the callback function. It can then be saved and used in the
-same manner as the function object. In other cases, you may have to
-construct a new tuple to pass as the argument list. The simplest way
-to do this is to call \cfunction{Py_BuildValue()}. For example, if
-you want to pass an integral event code, you might use the following
-code:
-
-\begin{verbatim}
- PyObject *arglist;
- ...
- arglist = Py_BuildValue("(l)", eventcode);
- result = PyEval_CallObject(my_callback, arglist);
- Py_DECREF(arglist);
- if (result == NULL)
- return NULL; /* Pass error back */
- /* Here maybe use the result */
- Py_DECREF(result);
-\end{verbatim}
-
-Note the placement of \samp{Py_DECREF(arglist)} immediately after the
-call, before the error check! Also note that strictly spoken this
-code is not complete: \cfunction{Py_BuildValue()} may run out of
-memory, and this should be checked.
-
-
-\section{Extracting Parameters in Extension Functions
- \label{parseTuple}}
-
-\ttindex{PyArg_ParseTuple()}
-
-The \cfunction{PyArg_ParseTuple()} function is declared as follows:
-
-\begin{verbatim}
-int PyArg_ParseTuple(PyObject *arg, char *format, ...);
-\end{verbatim}
-
-The \var{arg} argument must be a tuple object containing an argument
-list passed from Python to a C function. The \var{format} argument
-must be a format string, whose syntax is explained in
-``\ulink{Parsing arguments and building
-values}{../api/arg-parsing.html}'' in the
-\citetitle[../api/api.html]{Python/C API Reference Manual}. The
-remaining arguments must be addresses of variables whose type is
-determined by the format string.
-
-Note that while \cfunction{PyArg_ParseTuple()} checks that the Python
-arguments have the required types, it cannot check the validity of the
-addresses of C variables passed to the call: if you make mistakes
-there, your code will probably crash or at least overwrite random bits
-in memory. So be careful!
-
-Note that any Python object references which are provided to the
-caller are \emph{borrowed} references; do not decrement their
-reference count!
-
-Some example calls:
-
-\begin{verbatim}
- int ok;
- int i, j;
- long k, l;
- char *s;
- int size;
-
- ok = PyArg_ParseTuple(args, ""); /* No arguments */
- /* Python call: f() */
-\end{verbatim}
-
-\begin{verbatim}
- ok = PyArg_ParseTuple(args, "s", &s); /* A string */
- /* Possible Python call: f('whoops!') */
-\end{verbatim}
-
-\begin{verbatim}
- ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
- /* Possible Python call: f(1, 2, 'three') */
-\end{verbatim}
-
-\begin{verbatim}
- ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
- /* A pair of ints and a string, whose size is also returned */
- /* Possible Python call: f((1, 2), 'three') */
-\end{verbatim}
-
-\begin{verbatim}
- {
- char *file;
- char *mode = "r";
- int bufsize = 0;
- ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
- /* A string, and optionally another string and an integer */
- /* Possible Python calls:
- f('spam')
- f('spam', 'w')
- f('spam', 'wb', 100000) */
- }
-\end{verbatim}
-
-\begin{verbatim}
- {
- int left, top, right, bottom, h, v;
- ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
- &left, &top, &right, &bottom, &h, &v);
- /* A rectangle and a point */
- /* Possible Python call:
- f(((0, 0), (400, 300)), (10, 10)) */
- }
-\end{verbatim}
-
-\begin{verbatim}
- {
- Py_complex c;
- ok = PyArg_ParseTuple(args, "D:myfunction", &c);
- /* a complex, also providing a function name for errors */
- /* Possible Python call: myfunction(1+2j) */
- }
-\end{verbatim}
-
-
-\section{Keyword Parameters for Extension Functions
- \label{parseTupleAndKeywords}}
-
-\ttindex{PyArg_ParseTupleAndKeywords()}
-
-The \cfunction{PyArg_ParseTupleAndKeywords()} function is declared as
-follows:
-
-\begin{verbatim}
-int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
- char *format, char *kwlist[], ...);
-\end{verbatim}
-
-The \var{arg} and \var{format} parameters are identical to those of the
-\cfunction{PyArg_ParseTuple()} function. The \var{kwdict} parameter
-is the dictionary of keywords received as the third parameter from the
-Python runtime. The \var{kwlist} parameter is a \NULL-terminated
-list of strings which identify the parameters; the names are matched
-with the type information from \var{format} from left to right. On
-success, \cfunction{PyArg_ParseTupleAndKeywords()} returns true,
-otherwise it returns false and raises an appropriate exception.
-
-\note{Nested tuples cannot be parsed when using keyword
-arguments! Keyword parameters passed in which are not present in the
-\var{kwlist} will cause \exception{TypeError} to be raised.}
-
-Here is an example module which uses keywords, based on an example by
-Geoff Philbrick (\email{philbrick@hks.com}):%
-\index{Philbrick, Geoff}
-
-\begin{verbatim}
-#include "Python.h"
-
-static PyObject *
-keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
-{
- int voltage;
- char *state = "a stiff";
- char *action = "voom";
- char *type = "Norwegian Blue";
-
- static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
- &voltage, &state, &action, &type))
- return NULL;
-
- printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
- action, voltage);
- printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);
-
- Py_INCREF(Py_None);
-
- return Py_None;
-}
-
-static PyMethodDef keywdarg_methods[] = {
- /* The cast of the function is necessary since PyCFunction values
- * only take two PyObject* parameters, and keywdarg_parrot() takes
- * three.
- */
- {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
- "Print a lovely skit to standard output."},
- {NULL, NULL, 0, NULL} /* sentinel */
-};
-\end{verbatim}
-
-\begin{verbatim}
-void
-initkeywdarg(void)
-{
- /* Create the module and add the functions */
- Py_InitModule("keywdarg", keywdarg_methods);
-}
-\end{verbatim}
-
-
-\section{Building Arbitrary Values
- \label{buildValue}}
-
-This function is the counterpart to \cfunction{PyArg_ParseTuple()}. It is
-declared as follows:
-
-\begin{verbatim}
-PyObject *Py_BuildValue(char *format, ...);
-\end{verbatim}
-
-It recognizes a set of format units similar to the ones recognized by
-\cfunction{PyArg_ParseTuple()}, but the arguments (which are input to the
-function, not output) must not be pointers, just values. It returns a
-new Python object, suitable for returning from a C function called
-from Python.
-
-One difference with \cfunction{PyArg_ParseTuple()}: while the latter
-requires its first argument to be a tuple (since Python argument lists
-are always represented as tuples internally),
-\cfunction{Py_BuildValue()} does not always build a tuple. It builds
-a tuple only if its format string contains two or more format units.
-If the format string is empty, it returns \code{None}; if it contains
-exactly one format unit, it returns whatever object is described by
-that format unit. To force it to return a tuple of size 0 or one,
-parenthesize the format string.
-
-Examples (to the left the call, to the right the resulting Python value):
-
-\begin{verbatim}
- Py_BuildValue("") None
- Py_BuildValue("i", 123) 123
- Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
- Py_BuildValue("s", "hello") 'hello'
- Py_BuildValue("ss", "hello", "world") ('hello', 'world')
- Py_BuildValue("s#", "hello", 4) 'hell'
- Py_BuildValue("()") ()
- Py_BuildValue("(i)", 123) (123,)
- Py_BuildValue("(ii)", 123, 456) (123, 456)
- Py_BuildValue("(i,i)", 123, 456) (123, 456)
- Py_BuildValue("[i,i]", 123, 456) [123, 456]
- Py_BuildValue("{s:i,s:i}",
- "abc", 123, "def", 456) {'abc': 123, 'def': 456}
- Py_BuildValue("((ii)(ii)) (ii)",
- 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))
-\end{verbatim}
-
-
-\section{Reference Counts
- \label{refcounts}}
-
-In languages like C or \Cpp, the programmer is responsible for
-dynamic allocation and deallocation of memory on the heap. In C,
-this is done using the functions \cfunction{malloc()} and
-\cfunction{free()}. In \Cpp, the operators \keyword{new} and
-\keyword{delete} are used with essentially the same meaning and
-we'll restrict the following discussion to the latter.
-
-Every block of memory allocated with \cfunction{malloc()} should
-eventually be returned to the pool of available memory by exactly one
-call to \cfunction{free()}. It is important to call
-\cfunction{free()} at the right time. If a block's address is
-forgotten but \cfunction{free()} is not called for it, the memory it
-occupies cannot be reused until the program terminates. This is
-called a \dfn{memory leak}. On the other hand, if a program calls
-\cfunction{free()} for a block and then continues to use the block, it
-creates a conflict with re-use of the block through another
-\cfunction{malloc()} call. This is called \dfn{using freed memory}.
-It has the same bad consequences as referencing uninitialized data ---
-core dumps, wrong results, mysterious crashes.
-
-Common causes of memory leaks are unusual paths through the code. For
-instance, a function may allocate a block of memory, do some
-calculation, and then free the block again. Now a change in the
-requirements for the function may add a test to the calculation that
-detects an error condition and can return prematurely from the
-function. It's easy to forget to free the allocated memory block when
-taking this premature exit, especially when it is added later to the
-code. Such leaks, once introduced, often go undetected for a long
-time: the error exit is taken only in a small fraction of all calls,
-and most modern machines have plenty of virtual memory, so the leak
-only becomes apparent in a long-running process that uses the leaking
-function frequently. Therefore, it's important to prevent leaks from
-happening by having a coding convention or strategy that minimizes
-this kind of errors.
-
-Since Python makes heavy use of \cfunction{malloc()} and
-\cfunction{free()}, it needs a strategy to avoid memory leaks as well
-as the use of freed memory. The chosen method is called
-\dfn{reference counting}. The principle is simple: every object
-contains a counter, which is incremented when a reference to the
-object is stored somewhere, and which is decremented when a reference
-to it is deleted. When the counter reaches zero, the last reference
-to the object has been deleted and the object is freed.
-
-An alternative strategy is called \dfn{automatic garbage collection}.
-(Sometimes, reference counting is also referred to as a garbage
-collection strategy, hence my use of ``automatic'' to distinguish the
-two.) The big advantage of automatic garbage collection is that the
-user doesn't need to call \cfunction{free()} explicitly. (Another claimed
-advantage is an improvement in speed or memory usage --- this is no
-hard fact however.) The disadvantage is that for C, there is no
-truly portable automatic garbage collector, while reference counting
-can be implemented portably (as long as the functions \cfunction{malloc()}
-and \cfunction{free()} are available --- which the C Standard guarantees).
-Maybe some day a sufficiently portable automatic garbage collector
-will be available for C. Until then, we'll have to live with
-reference counts.
-
-While Python uses the traditional reference counting implementation,
-it also offers a cycle detector that works to detect reference
-cycles. This allows applications to not worry about creating direct
-or indirect circular references; these are the weakness of garbage
-collection implemented using only reference counting. Reference
-cycles consist of objects which contain (possibly indirect) references
-to themselves, so that each object in the cycle has a reference count
-which is non-zero. Typical reference counting implementations are not
-able to reclaim the memory belonging to any objects in a reference
-cycle, or referenced from the objects in the cycle, even though there
-are no further references to the cycle itself.
-
-The cycle detector is able to detect garbage cycles and can reclaim
-them so long as there are no finalizers implemented in Python
-(\method{__del__()} methods). When there are such finalizers, the
-detector exposes the cycles through the \ulink{\module{gc}
-module}{../lib/module-gc.html} (specifically, the \code{garbage}
-variable in that module). The \module{gc} module also exposes a way
-to run the detector (the \function{collect()} function), as well as
-configuration interfaces and the ability to disable the detector at
-runtime. The cycle detector is considered an optional component;
-though it is included by default, it can be disabled at build time
-using the \longprogramopt{without-cycle-gc} option to the
-\program{configure} script on \UNIX{} platforms (including Mac OS X)
-or by removing the definition of \code{WITH_CYCLE_GC} in the
-\file{pyconfig.h} header on other platforms. If the cycle detector is
-disabled in this way, the \module{gc} module will not be available.
-
-
-\subsection{Reference Counting in Python
- \label{refcountsInPython}}
-
-There are two macros, \code{Py_INCREF(x)} and \code{Py_DECREF(x)},
-which handle the incrementing and decrementing of the reference count.
-\cfunction{Py_DECREF()} also frees the object when the count reaches zero.
-For flexibility, it doesn't call \cfunction{free()} directly --- rather, it
-makes a call through a function pointer in the object's \dfn{type
-object}. For this purpose (and others), every object also contains a
-pointer to its type object.
-
-The big question now remains: when to use \code{Py_INCREF(x)} and
-\code{Py_DECREF(x)}? Let's first introduce some terms. Nobody
-``owns'' an object; however, you can \dfn{own a reference} to an
-object. An object's reference count is now defined as the number of
-owned references to it. The owner of a reference is responsible for
-calling \cfunction{Py_DECREF()} when the reference is no longer
-needed. Ownership of a reference can be transferred. There are three
-ways to dispose of an owned reference: pass it on, store it, or call
-\cfunction{Py_DECREF()}. Forgetting to dispose of an owned reference
-creates a memory leak.
-
-It is also possible to \dfn{borrow}\footnote{The metaphor of
-``borrowing'' a reference is not completely correct: the owner still
-has a copy of the reference.} a reference to an object. The borrower
-of a reference should not call \cfunction{Py_DECREF()}. The borrower must
-not hold on to the object longer than the owner from which it was
-borrowed. Using a borrowed reference after the owner has disposed of
-it risks using freed memory and should be avoided
-completely.\footnote{Checking that the reference count is at least 1
-\strong{does not work} --- the reference count itself could be in
-freed memory and may thus be reused for another object!}
-
-The advantage of borrowing over owning a reference is that you don't
-need to take care of disposing of the reference on all possible paths
-through the code --- in other words, with a borrowed reference you
-don't run the risk of leaking when a premature exit is taken. The
-disadvantage of borrowing over leaking is that there are some subtle
-situations where in seemingly correct code a borrowed reference can be
-used after the owner from which it was borrowed has in fact disposed
-of it.
-
-A borrowed reference can be changed into an owned reference by calling
-\cfunction{Py_INCREF()}. This does not affect the status of the owner from
-which the reference was borrowed --- it creates a new owned reference,
-and gives full owner responsibilities (the new owner must
-dispose of the reference properly, as well as the previous owner).
-
-
-\subsection{Ownership Rules
- \label{ownershipRules}}
-
-Whenever an object reference is passed into or out of a function, it
-is part of the function's interface specification whether ownership is
-transferred with the reference or not.
-
-Most functions that return a reference to an object pass on ownership
-with the reference. In particular, all functions whose function it is
-to create a new object, such as \cfunction{PyInt_FromLong()} and
-\cfunction{Py_BuildValue()}, pass ownership to the receiver. Even if
-the object is not actually new, you still receive ownership of a new
-reference to that object. For instance, \cfunction{PyInt_FromLong()}
-maintains a cache of popular values and can return a reference to a
-cached item.
-
-Many functions that extract objects from other objects also transfer
-ownership with the reference, for instance
-\cfunction{PyObject_GetAttrString()}. The picture is less clear, here,
-however, since a few common routines are exceptions:
-\cfunction{PyTuple_GetItem()}, \cfunction{PyList_GetItem()},
-\cfunction{PyDict_GetItem()}, and \cfunction{PyDict_GetItemString()}
-all return references that you borrow from the tuple, list or
-dictionary.
-
-The function \cfunction{PyImport_AddModule()} also returns a borrowed
-reference, even though it may actually create the object it returns:
-this is possible because an owned reference to the object is stored in
-\code{sys.modules}.
-
-When you pass an object reference into another function, in general,
-the function borrows the reference from you --- if it needs to store
-it, it will use \cfunction{Py_INCREF()} to become an independent
-owner. There are exactly two important exceptions to this rule:
-\cfunction{PyTuple_SetItem()} and \cfunction{PyList_SetItem()}. These
-functions take over ownership of the item passed to them --- even if
-they fail! (Note that \cfunction{PyDict_SetItem()} and friends don't
-take over ownership --- they are ``normal.'')
-
-When a C function is called from Python, it borrows references to its
-arguments from the caller. The caller owns a reference to the object,
-so the borrowed reference's lifetime is guaranteed until the function
-returns. Only when such a borrowed reference must be stored or passed
-on, it must be turned into an owned reference by calling
-\cfunction{Py_INCREF()}.
-
-The object reference returned from a C function that is called from
-Python must be an owned reference --- ownership is tranferred from the
-function to its caller.
-
-
-\subsection{Thin Ice
- \label{thinIce}}
-
-There are a few situations where seemingly harmless use of a borrowed
-reference can lead to problems. These all have to do with implicit
-invocations of the interpreter, which can cause the owner of a
-reference to dispose of it.
-
-The first and most important case to know about is using
-\cfunction{Py_DECREF()} on an unrelated object while borrowing a
-reference to a list item. For instance:
-
-\begin{verbatim}
-void
-bug(PyObject *list)
-{
- PyObject *item = PyList_GetItem(list, 0);
-
- PyList_SetItem(list, 1, PyInt_FromLong(0L));
- PyObject_Print(item, stdout, 0); /* BUG! */
-}
-\end{verbatim}
-
-This function first borrows a reference to \code{list[0]}, then
-replaces \code{list[1]} with the value \code{0}, and finally prints
-the borrowed reference. Looks harmless, right? But it's not!
-
-Let's follow the control flow into \cfunction{PyList_SetItem()}. The list
-owns references to all its items, so when item 1 is replaced, it has
-to dispose of the original item 1. Now let's suppose the original
-item 1 was an instance of a user-defined class, and let's further
-suppose that the class defined a \method{__del__()} method. If this
-class instance has a reference count of 1, disposing of it will call
-its \method{__del__()} method.
-
-Since it is written in Python, the \method{__del__()} method can execute
-arbitrary Python code. Could it perhaps do something to invalidate
-the reference to \code{item} in \cfunction{bug()}? You bet! Assuming
-that the list passed into \cfunction{bug()} is accessible to the
-\method{__del__()} method, it could execute a statement to the effect of
-\samp{del list[0]}, and assuming this was the last reference to that
-object, it would free the memory associated with it, thereby
-invalidating \code{item}.
-
-The solution, once you know the source of the problem, is easy:
-temporarily increment the reference count. The correct version of the
-function reads:
-
-\begin{verbatim}
-void
-no_bug(PyObject *list)
-{
- PyObject *item = PyList_GetItem(list, 0);
-
- Py_INCREF(item);
- PyList_SetItem(list, 1, PyInt_FromLong(0L));
- PyObject_Print(item, stdout, 0);
- Py_DECREF(item);
-}
-\end{verbatim}
-
-This is a true story. An older version of Python contained variants
-of this bug and someone spent a considerable amount of time in a C
-debugger to figure out why his \method{__del__()} methods would fail...
-
-The second case of problems with a borrowed reference is a variant
-involving threads. Normally, multiple threads in the Python
-interpreter can't get in each other's way, because there is a global
-lock protecting Python's entire object space. However, it is possible
-to temporarily release this lock using the macro
-\csimplemacro{Py_BEGIN_ALLOW_THREADS}, and to re-acquire it using
-\csimplemacro{Py_END_ALLOW_THREADS}. This is common around blocking
-I/O calls, to let other threads use the processor while waiting for
-the I/O to complete. Obviously, the following function has the same
-problem as the previous one:
-
-\begin{verbatim}
-void
-bug(PyObject *list)
-{
- PyObject *item = PyList_GetItem(list, 0);
- Py_BEGIN_ALLOW_THREADS
- ...some blocking I/O call...
- Py_END_ALLOW_THREADS
- PyObject_Print(item, stdout, 0); /* BUG! */
-}
-\end{verbatim}
-
-
-\subsection{NULL Pointers
- \label{nullPointers}}
-
-In general, functions that take object references as arguments do not
-expect you to pass them \NULL{} pointers, and will dump core (or
-cause later core dumps) if you do so. Functions that return object
-references generally return \NULL{} only to indicate that an
-exception occurred. The reason for not testing for \NULL{}
-arguments is that functions often pass the objects they receive on to
-other function --- if each function were to test for \NULL,
-there would be a lot of redundant tests and the code would run more
-slowly.
-
-It is better to test for \NULL{} only at the ``source:'' when a
-pointer that may be \NULL{} is received, for example, from
-\cfunction{malloc()} or from a function that may raise an exception.
-
-The macros \cfunction{Py_INCREF()} and \cfunction{Py_DECREF()}
-do not check for \NULL{} pointers --- however, their variants
-\cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()} do.
-
-The macros for checking for a particular object type
-(\code{Py\var{type}_Check()}) don't check for \NULL{} pointers ---
-again, there is much code that calls several of these in a row to test
-an object against various different expected types, and this would
-generate redundant tests. There are no variants with \NULL{}
-checking.
-
-The C function calling mechanism guarantees that the argument list
-passed to C functions (\code{args} in the examples) is never
-\NULL{} --- in fact it guarantees that it is always a tuple.\footnote{
-These guarantees don't hold when you use the ``old'' style
-calling convention --- this is still found in much existing code.}
-
-It is a severe error to ever let a \NULL{} pointer ``escape'' to
-the Python user.
-
-% Frank Stajano:
-% A pedagogically buggy example, along the lines of the previous listing,
-% would be helpful here -- showing in more concrete terms what sort of
-% actions could cause the problem. I can't very well imagine it from the
-% description.
-
-
-\section{Writing Extensions in \Cpp
- \label{cplusplus}}
-
-It is possible to write extension modules in \Cpp. Some restrictions
-apply. If the main program (the Python interpreter) is compiled and
-linked by the C compiler, global or static objects with constructors
-cannot be used. This is not a problem if the main program is linked
-by the \Cpp{} compiler. Functions that will be called by the
-Python interpreter (in particular, module initalization functions)
-have to be declared using \code{extern "C"}.
-It is unnecessary to enclose the Python header files in
-\code{extern "C" \{...\}} --- they use this form already if the symbol
-\samp{__cplusplus} is defined (all recent \Cpp{} compilers define this
-symbol).
-
-
-\section{Providing a C API for an Extension Module
- \label{using-cobjects}}
-\sectionauthor{Konrad Hinsen}{hinsen@cnrs-orleans.fr}
-
-Many extension modules just provide new functions and types to be
-used from Python, but sometimes the code in an extension module can
-be useful for other extension modules. For example, an extension
-module could implement a type ``collection'' which works like lists
-without order. Just like the standard Python list type has a C API
-which permits extension modules to create and manipulate lists, this
-new collection type should have a set of C functions for direct
-manipulation from other extension modules.
-
-At first sight this seems easy: just write the functions (without
-declaring them \keyword{static}, of course), provide an appropriate
-header file, and document the C API. And in fact this would work if
-all extension modules were always linked statically with the Python
-interpreter. When modules are used as shared libraries, however, the
-symbols defined in one module may not be visible to another module.
-The details of visibility depend on the operating system; some systems
-use one global namespace for the Python interpreter and all extension
-modules (Windows, for example), whereas others require an explicit
-list of imported symbols at module link time (AIX is one example), or
-offer a choice of different strategies (most Unices). And even if
-symbols are globally visible, the module whose functions one wishes to
-call might not have been loaded yet!
-
-Portability therefore requires not to make any assumptions about
-symbol visibility. This means that all symbols in extension modules
-should be declared \keyword{static}, except for the module's
-initialization function, in order to avoid name clashes with other
-extension modules (as discussed in section~\ref{methodTable}). And it
-means that symbols that \emph{should} be accessible from other
-extension modules must be exported in a different way.
-
-Python provides a special mechanism to pass C-level information
-(pointers) from one extension module to another one: CObjects.
-A CObject is a Python data type which stores a pointer (\ctype{void
-*}). CObjects can only be created and accessed via their C API, but
-they can be passed around like any other Python object. In particular,
-they can be assigned to a name in an extension module's namespace.
-Other extension modules can then import this module, retrieve the
-value of this name, and then retrieve the pointer from the CObject.
-
-There are many ways in which CObjects can be used to export the C API
-of an extension module. Each name could get its own CObject, or all C
-API pointers could be stored in an array whose address is published in
-a CObject. And the various tasks of storing and retrieving the pointers
-can be distributed in different ways between the module providing the
-code and the client modules.
-
-The following example demonstrates an approach that puts most of the
-burden on the writer of the exporting module, which is appropriate
-for commonly used library modules. It stores all C API pointers
-(just one in the example!) in an array of \ctype{void} pointers which
-becomes the value of a CObject. The header file corresponding to
-the module provides a macro that takes care of importing the module
-and retrieving its C API pointers; client modules only have to call
-this macro before accessing the C API.
-
-The exporting module is a modification of the \module{spam} module from
-section~\ref{simpleExample}. The function \function{spam.system()}
-does not call the C library function \cfunction{system()} directly,
-but a function \cfunction{PySpam_System()}, which would of course do
-something more complicated in reality (such as adding ``spam'' to
-every command). This function \cfunction{PySpam_System()} is also
-exported to other extension modules.
-
-The function \cfunction{PySpam_System()} is a plain C function,
-declared \keyword{static} like everything else:
-
-\begin{verbatim}
-static int
-PySpam_System(char *command)
-{
- return system(command);
-}
-\end{verbatim}
-
-The function \cfunction{spam_system()} is modified in a trivial way:
-
-\begin{verbatim}
-static PyObject *
-spam_system(PyObject *self, PyObject *args)
-{
- char *command;
- int sts;
-
- if (!PyArg_ParseTuple(args, "s", &command))
- return NULL;
- sts = PySpam_System(command);
- return Py_BuildValue("i", sts);
-}
-\end{verbatim}
-
-In the beginning of the module, right after the line
-
-\begin{verbatim}
-#include "Python.h"
-\end{verbatim}
-
-two more lines must be added:
-
-\begin{verbatim}
-#define SPAM_MODULE
-#include "spammodule.h"
-\end{verbatim}
-
-The \code{\#define} is used to tell the header file that it is being
-included in the exporting module, not a client module. Finally,
-the module's initialization function must take care of initializing
-the C API pointer array:
-
-\begin{verbatim}
-PyMODINIT_FUNC
-initspam(void)
-{
- PyObject *m;
- static void *PySpam_API[PySpam_API_pointers];
- PyObject *c_api_object;
-
- m = Py_InitModule("spam", SpamMethods);
-
- /* Initialize the C API pointer array */
- PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;
-
- /* Create a CObject containing the API pointer array's address */
- c_api_object = PyCObject_FromVoidPtr((void *)PySpam_API, NULL);
-
- if (c_api_object != NULL)
- PyModule_AddObject(m, "_C_API", c_api_object);
-}
-\end{verbatim}
-
-Note that \code{PySpam_API} is declared \keyword{static}; otherwise
-the pointer array would disappear when \function{initspam()} terminates!
-
-The bulk of the work is in the header file \file{spammodule.h},
-which looks like this:
-
-\begin{verbatim}
-#ifndef Py_SPAMMODULE_H
-#define Py_SPAMMODULE_H
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Header file for spammodule */
-
-/* C API functions */
-#define PySpam_System_NUM 0
-#define PySpam_System_RETURN int
-#define PySpam_System_PROTO (char *command)
-
-/* Total number of C API pointers */
-#define PySpam_API_pointers 1
-
-
-#ifdef SPAM_MODULE
-/* This section is used when compiling spammodule.c */
-
-static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;
-
-#else
-/* This section is used in modules that use spammodule's API */
-
-static void **PySpam_API;
-
-#define PySpam_System \
- (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])
-
-/* Return -1 and set exception on error, 0 on success. */
-static int
-import_spam(void)
-{
- PyObject *module = PyImport_ImportModule("spam");
-
- if (module != NULL) {
- PyObject *c_api_object = PyObject_GetAttrString(module, "_C_API");
- if (c_api_object == NULL)
- return -1;
- if (PyCObject_Check(c_api_object))
- PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object);
- Py_DECREF(c_api_object);
- }
- return 0;
-}
-
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* !defined(Py_SPAMMODULE_H) */
-\end{verbatim}
-
-All that a client module must do in order to have access to the
-function \cfunction{PySpam_System()} is to call the function (or
-rather macro) \cfunction{import_spam()} in its initialization
-function:
-
-\begin{verbatim}
-PyMODINIT_FUNC
-initclient(void)
-{
- PyObject *m;
-
- Py_InitModule("client", ClientMethods);
- if (import_spam() < 0)
- return;
- /* additional initialization can happen here */
-}
-\end{verbatim}
-
-The main disadvantage of this approach is that the file
-\file{spammodule.h} is rather complicated. However, the
-basic structure is the same for each function that is
-exported, so it has to be learned only once.
-
-Finally it should be mentioned that CObjects offer additional
-functionality, which is especially useful for memory allocation and
-deallocation of the pointer stored in a CObject. The details
-are described in the \citetitle[../api/api.html]{Python/C API
-Reference Manual} in the section
-``\ulink{CObjects}{../api/cObjects.html}'' and in the implementation
-of CObjects (files \file{Include/cobject.h} and
-\file{Objects/cobject.c} in the Python source code distribution).
diff --git a/Doc/ext/newtypes.tex b/Doc/ext/newtypes.tex
deleted file mode 100644
index 8b300aaee5..0000000000
--- a/Doc/ext/newtypes.tex
+++ /dev/null
@@ -1,1366 +0,0 @@
-\chapter{Defining New Types
- \label{defining-new-types}}
-\sectionauthor{Michael Hudson}{mwh@python.net}
-\sectionauthor{Dave Kuhlman}{dkuhlman@rexx.com}
-\sectionauthor{Jim Fulton}{jim@zope.com}
-
-As mentioned in the last chapter, Python allows the writer of an
-extension module to define new types that can be manipulated from
-Python code, much like strings and lists in core Python.
-
-This is not hard; the code for all extension types follows a pattern,
-but there are some details that you need to understand before you can
-get started.
-
-\begin{notice}
-The way new types are defined changed dramatically (and for the
-better) in Python 2.2. This document documents how to define new
-types for Python 2.2 and later. If you need to support older
-versions of Python, you will need to refer to older versions of this
-documentation.
-\end{notice}
-
-\section{The Basics
- \label{dnt-basics}}
-
-The Python runtime sees all Python objects as variables of type
-\ctype{PyObject*}. A \ctype{PyObject} is not a very magnificent
-object - it just contains the refcount and a pointer to the object's
-``type object''. This is where the action is; the type object
-determines which (C) functions get called when, for instance, an
-attribute gets looked up on an object or it is multiplied by another
-object. These C functions are called ``type methods'' to distinguish
-them from things like \code{[].append} (which we call ``object
-methods'').
-
-So, if you want to define a new object type, you need to create a new
-type object.
-
-This sort of thing can only be explained by example, so here's a
-minimal, but complete, module that defines a new type:
-
-\verbatiminput{noddy.c}
-
-Now that's quite a bit to take in at once, but hopefully bits will
-seem familiar from the last chapter.
-
-The first bit that will be new is:
-
-\begin{verbatim}
-typedef struct {
- PyObject_HEAD
-} noddy_NoddyObject;
-\end{verbatim}
-
-This is what a Noddy object will contain---in this case, nothing more
-than every Python object contains, namely a refcount and a pointer to a type
-object. These are the fields the \code{PyObject_HEAD} macro brings
-in. The reason for the macro is to standardize the layout and to
-enable special debugging fields in debug builds. Note that there is
-no semicolon after the \code{PyObject_HEAD} macro; one is included in
-the macro definition. Be wary of adding one by accident; it's easy to
-do from habit, and your compiler might not complain, but someone
-else's probably will! (On Windows, MSVC is known to call this an
-error and refuse to compile the code.)
-
-For contrast, let's take a look at the corresponding definition for
-standard Python integers:
-
-\begin{verbatim}
-typedef struct {
- PyObject_HEAD
- long ob_ival;
-} PyIntObject;
-\end{verbatim}
-
-Moving on, we come to the crunch --- the type object.
-
-\begin{verbatim}
-static PyTypeObject noddy_NoddyType = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "noddy.Noddy", /*tp_name*/
- sizeof(noddy_NoddyObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- 0, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Noddy objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
-};
-\end{verbatim}
-
-Now if you go and look up the definition of \ctype{PyTypeObject} in
-\file{object.h} you'll see that it has many more fields that the
-definition above. The remaining fields will be filled with zeros by
-the C compiler, and it's common practice to not specify them
-explicitly unless you need them.
-
-This is so important that we're going to pick the top of it apart still
-further:
-
-\begin{verbatim}
- PyObject_HEAD_INIT(NULL)
-\end{verbatim}
-
-This line is a bit of a wart; what we'd like to write is:
-
-\begin{verbatim}
- PyObject_HEAD_INIT(&PyType_Type)
-\end{verbatim}
-
-as the type of a type object is ``type'', but this isn't strictly
-conforming C and some compilers complain. Fortunately, this member
-will be filled in for us by \cfunction{PyType_Ready()}.
-
-\begin{verbatim}
- 0, /* ob_size */
-\end{verbatim}
-
-The \member{ob_size} field of the header is not used; its presence in
-the type structure is a historical artifact that is maintained for
-binary compatibility with extension modules compiled for older
-versions of Python. Always set this field to zero.
-
-\begin{verbatim}
- "noddy.Noddy", /* tp_name */
-\end{verbatim}
-
-The name of our type. This will appear in the default textual
-representation of our objects and in some error messages, for example:
-
-\begin{verbatim}
->>> "" + noddy.new_noddy()
-Traceback (most recent call last):
- File "", line 1, in ?
-TypeError: cannot add type "noddy.Noddy" to string
-\end{verbatim}
-
-Note that the name is a dotted name that includes both the module name
-and the name of the type within the module. The module in this case is
-\module{noddy} and the type is \class{Noddy}, so we set the type name
-to \class{noddy.Noddy}.
-
-\begin{verbatim}
- sizeof(noddy_NoddyObject), /* tp_basicsize */
-\end{verbatim}
-
-This is so that Python knows how much memory to allocate when you call
-\cfunction{PyObject_New}.
-
-\begin{verbatim}
- 0, /* tp_itemsize */
-\end{verbatim}
-
-This has to do with variable length objects like lists and strings.
-Ignore this for now.
-
-Skipping a number of type methods that we don't provide, we set the
-class flags to \constant{Py_TPFLAGS_DEFAULT}.
-
-\begin{verbatim}
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
-\end{verbatim}
-
-All types should include this constant in their flags. It enables all
-of the members defined by the current version of Python.
-
-We provide a doc string for the type in \member{tp_doc}.
-
-\begin{verbatim}
- "Noddy objects", /* tp_doc */
-\end{verbatim}
-
-Now we get into the type methods, the things that make your objects
-different from the others. We aren't going to implement any of these
-in this version of the module. We'll expand this example later to
-have more interesting behavior.
-
-For now, all we want to be able to do is to create new \class{Noddy}
-objects. To enable object creation, we have to provide a
-\member{tp_new} implementation. In this case, we can just use the
-default implementation provided by the API function
-\cfunction{PyType_GenericNew}.
-
-\begin{verbatim}
- PyType_GenericNew, /* tp_new */
-\end{verbatim}
-
-All the other type methods are \NULL, so we'll go over them later
---- that's for a later section!
-
-Everything else in the file should be familiar, except for some code
-in \cfunction{initnoddy}:
-
-\begin{verbatim}
- if (PyType_Ready(&noddy_NoddyType) < 0)
- return;
-\end{verbatim}
-
-This initializes the \class{Noddy} type, filing in a number of
-members, including \member{ob_type} that we initially set to \NULL.
-
-\begin{verbatim}
- PyModule_AddObject(m, "Noddy", (PyObject *)&noddy_NoddyType);
-\end{verbatim}
-
-This adds the type to the module dictionary. This allows us to create
-\class{Noddy} instances by calling the \class{Noddy} class:
-
-\begin{verbatim}
-import noddy
-mynoddy = noddy.Noddy()
-\end{verbatim}
-
-That's it! All that remains is to build it; put the above code in a
-file called \file{noddy.c} and
-
-\begin{verbatim}
-from distutils.core import setup, Extension
-setup(name="noddy", version="1.0",
- ext_modules=[Extension("noddy", ["noddy.c"])])
-\end{verbatim}
-
-in a file called \file{setup.py}; then typing
-
-\begin{verbatim}
-$ python setup.py build
-\end{verbatim} %$ <-- bow to font-lock ;-(
-
-at a shell should produce a file \file{noddy.so} in a subdirectory;
-move to that directory and fire up Python --- you should be able to
-\code{import noddy} and play around with Noddy objects.
-
-That wasn't so hard, was it?
-
-Of course, the current Noddy type is pretty uninteresting. It has no
-data and doesn't do anything. It can't even be subclassed.
-
-\subsection{Adding data and methods to the Basic example}
-
-Let's expend the basic example to add some data and methods. Let's
-also make the type usable as a base class. We'll create
-a new module, \module{noddy2} that adds these capabilities:
-
-\verbatiminput{noddy2.c}
-
-This version of the module has a number of changes.
-
-We've added an extra include:
-
-\begin{verbatim}
-#include "structmember.h"
-\end{verbatim}
-
-This include provides declarations that we use to handle attributes,
-as described a bit later.
-
-The name of the \class{Noddy} object structure has been shortened to
-\class{Noddy}. The type object name has been shortened to
-\class{NoddyType}.
-
-The \class{Noddy} type now has three data attributes, \var{first},
-\var{last}, and \var{number}. The \var{first} and \var{last}
-variables are Python strings containing first and last names. The
-\var{number} attribute is an integer.
-
-The object structure is updated accordingly:
-
-\begin{verbatim}
-typedef struct {
- PyObject_HEAD
- PyObject *first;
- PyObject *last;
- int number;
-} Noddy;
-\end{verbatim}
-
-Because we now have data to manage, we have to be more careful about
-object allocation and deallocation. At a minimum, we need a
-deallocation method:
-
-\begin{verbatim}
-static void
-Noddy_dealloc(Noddy* self)
-{
- Py_XDECREF(self->first);
- Py_XDECREF(self->last);
- self->ob_type->tp_free((PyObject*)self);
-}
-\end{verbatim}
-
-which is assigned to the \member{tp_dealloc} member:
-
-\begin{verbatim}
- (destructor)Noddy_dealloc, /*tp_dealloc*/
-\end{verbatim}
-
-This method decrements the reference counts of the two Python
-attributes. We use \cfunction{Py_XDECREF} here because the
-\member{first} and \member{last} members could be \NULL. It then
-calls the \member{tp_free} member of the object's type to free the
-object's memory. Note that the object's type might not be
-\class{NoddyType}, because the object may be an instance of a
-subclass.
-
-We want to make sure that the first and last names are initialized to
-empty strings, so we provide a new method:
-
-\begin{verbatim}
-static PyObject *
-Noddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
- Noddy *self;
-
- self = (Noddy *)type->tp_alloc(type, 0);
- if (self != NULL) {
- self->first = PyString_FromString("");
- if (self->first == NULL)
- {
- Py_DECREF(self);
- return NULL;
- }
-
- self->last = PyString_FromString("");
- if (self->last == NULL)
- {
- Py_DECREF(self);
- return NULL;
- }
-
- self->number = 0;
- }
-
- return (PyObject *)self;
-}
-\end{verbatim}
-
-and install it in the \member{tp_new} member:
-
-\begin{verbatim}
- Noddy_new, /* tp_new */
-\end{verbatim}
-
-The new member is responsible for creating (as opposed to
-initializing) objects of the type. It is exposed in Python as the
-\method{__new__} method. See the paper titled ``Unifying types and
-classes in Python'' for a detailed discussion of the \method{__new__}
-method. One reason to implement a new method is to assure the initial
-values of instance variables. In this case, we use the new method to
-make sure that the initial values of the members \member{first} and
-\member{last} are not \NULL. If we didn't care whether the initial
-values were \NULL, we could have used \cfunction{PyType_GenericNew} as
-our new method, as we did before. \cfunction{PyType_GenericNew}
-initializes all of the instance variable members to NULLs.
-
-The new method is a static method that is passed the type being
-instantiated and any arguments passed when the type was called,
-and that returns the new object created. New methods always accept
-positional and keyword arguments, but they often ignore the arguments,
-leaving the argument handling to initializer methods. Note that if the
-type supports subclassing, the type passed may not be the type being
-defined. The new method calls the tp_alloc slot to allocate memory.
-We don't fill the \member{tp_alloc} slot ourselves. Rather
-\cfunction{PyType_Ready()} fills it for us by inheriting it from our
-base class, which is \class{object} by default. Most types use the
-default allocation.
-
-We provide an initialization function:
-
-\begin{verbatim}
-static PyObject *
-Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
-{
- PyObject *first=NULL, *last=NULL;
-
- static char *kwlist[] = {"first", "last", "number", NULL};
-
- if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
- &first, &last,
- &self->number))
- return NULL;
-
- if (first) {
- Py_XDECREF(self->first);
- Py_INCREF(first);
- self->first = first;
- }
-
- if (last) {
- Py_XDECREF(self->last);
- Py_INCREF(last);
- self->last = last;
- }
-
- Py_INCREF(Py_None);
- return Py_None;
-}
-\end{verbatim}
-
-by filling the \member{tp_init} slot.
-
-\begin{verbatim}
- (initproc)Noddy_init, /* tp_init */
-\end{verbatim}
-
-The \member{tp_init} slot is exposed in Python as the
-\method{__init__} method. It is used to initialize an object after
-it's created. Unlike the new method, we can't guarantee that the
-initializer is called. The initializer isn't called when unpickling
-objects and it can be overridden. Our initializer accepts arguments
-to provide initial values for our instance. Initializers always accept
-positional and keyword arguments.
-
-We want to want to expose our instance variables as attributes. There
-are a number of ways to do that. The simplest way is to define member
-definitions:
-
-\begin{verbatim}
-static PyMemberDef Noddy_members[] = {
- {"first", T_OBJECT_EX, offsetof(Noddy, first), 0,
- "first name"},
- {"last", T_OBJECT_EX, offsetof(Noddy, last), 0,
- "last name"},
- {"number", T_INT, offsetof(Noddy, number), 0,
- "noddy number"},
- {NULL} /* Sentinel */
-};
-\end{verbatim}
-
-and put the definitions in the \member{tp_members} slot:
-
-\begin{verbatim}
- Noddy_members, /* tp_members */
-\end{verbatim}
-
-Each member definition has a member name, type, offset, access flags
-and documentation string. See the ``Generic Attribute Management''
-section below for details.
-
-A disadvantage of this approach is that it doesn't provide a way to
-restrict the types of objects that can be assigned to the Python
-attributes. We expect the first and last names to be strings, but any
-Python objects can be assigned. Further, the attributes can be
-deleted, setting the C pointers to \NULL. Even though we can make
-sure the members are initialized to non-\NULL values, the members can
-be set to \NULL if the attributes are deleted.
-
-We define a single method, \method{name}, that outputs the objects
-name as the concatenation of the first and last names.
-
-\begin{verbatim}
-static PyObject *
-Noddy_name(Noddy* self)
-{
- static PyObject *format = NULL;
- PyObject *args, *result;
-
- if (format == NULL) {
- format = PyString_FromString("%s %s");
- if (format == NULL)
- return NULL;
- }
-
- if (self->first == NULL) {
- PyErr_SetString(PyExc_AttributeError, "first");
- return NULL;
- }
-
- if (self->last == NULL) {
- PyErr_SetString(PyExc_AttributeError, "last");
- return NULL;
- }
-
- args = Py_BuildValue("OO", self->first, self->last);
- if (args == NULL)
- return NULL;
-
- result = PyString_Format(format, args);
- Py_DECREF(args);
-
- return result;
-}
-\end{verbatim}
-
-The method is implemented as a C function that takes a \class{Noddy} (or
-\class{Noddy} subclass) instance as the first argument. Methods
-always take an instance as the first argument. Methods often take
-positional and keyword arguments as well, but in this cased we don't
-take any and don't need to accept a positional argument tuple or
-keyword argument dictionary. This method is equivalent to the Python
-method:
-
-\begin{verbatim}
- def name(self):
- return "%s %s" % (self.first, self.last)
-\end{verbatim}
-
-Note that we have to check for the possibility that our \member{first}
-and \member{last} members are \NULL. This is because they can be
-deleted, in which case they are set to \NULL. It would be better to
-prevent deletion of these attributes and to restrict the attribute
-values to be strings. We'll see how to do that in the next section.
-
-Now that we've defined the method, we need to create an array of
-method definitions:
-
-\begin{verbatim}
-static PyMethodDef Noddy_methods[] = {
- {"name", (PyCFunction)Noddy_name, METH_NOARGS,
- "Return the name, combining the first and last name"
- },
- {NULL} /* Sentinel */
-};
-\end{verbatim}
-
-and assign them to the \member{tp_methods} slot:
-
-\begin{verbatim}
- Noddy_methods, /* tp_methods */
-\end{verbatim}
-
-Note that used the \constant{METH_NOARGS} flag to indicate that the
-method is passed no arguments.
-
-Finally, we'll make our type usable as a base class. We've written
-our methods carefully so far so that they don't make any assumptions
-about the type of the object being created or used, so all we need to
-do is to add the \constant{Py_TPFLAGS_BASETYPE} to our class flag
-definition:
-
-\begin{verbatim}
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
-\end{verbatim}
-
-We rename \cfunction{initnoddy} to \cfunction{initnoddy2}
-and update the module name passed to \cfunction{Py_InitModule3}.
-
-Finally, we update our \file{setup.py} file to build the new module:
-
-\begin{verbatim}
-from distutils.core import setup, Extension
-setup(name="noddy", version="1.0",
- ext_modules=[
- Extension("noddy", ["noddy.c"]),
- Extension("noddy2", ["noddy2.c"]),
- ])
-\end{verbatim}
-
-\subsection{Providing finer control over data attributes}
-
-In this section, we'll provide finer control over how the
-\member{first} and \member{last} attributes are set in the
-\class{Noddy} example. In the previous version of our module, the
-instance variables \member{first} and \member{last} could be set to
-non-string values or even deleted. We want to make sure that these
-attributes always contain strings.
-
-\verbatiminput{noddy3.c}
-
-To provide greater control, over the \member{first} and \member{last}
-attributes, we'll use custom getter and setter functions. Here are
-the functions for getting and setting the \member{first} attribute:
-
-\begin{verbatim}
-Noddy_getfirst(Noddy *self, void *closure)
-{
- Py_INCREF(self->first);
- return self->first;
-}
-
-static int
-Noddy_setfirst(Noddy *self, PyObject *value, void *closure)
-{
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
- return -1;
- }
-
- if (! PyString_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "The first attribute value must be a string");
- return -1;
- }
-
- Py_DECREF(self->first);
- Py_INCREF(value);
- self->first = value;
-
- return 0;
-}
-\end{verbatim}
-
-The getter function is passed a \class{Noddy} object and a
-``closure'', which is void pointer. In this case, the closure is
-ignored. (The closure supports an advanced usage in which definition
-data is passed to the getter and setter. This could, for example, be
-used to allow a single set of getter and setter functions that decide
-the attribute to get or set based on data in the closure.)
-
-The setter function is passed the \class{Noddy} object, the new value,
-and the closure. The new value may be \NULL, in which case the
-attribute is being deleted. In our setter, we raise an error if the
-attribute is deleted or if the attribute value is not a string.
-
-We create an array of \ctype{PyGetSetDef} structures:
-
-\begin{verbatim}
-static PyGetSetDef Noddy_getseters[] = {
- {"first",
- (getter)Noddy_getfirst, (setter)Noddy_setfirst,
- "first name",
- NULL},
- {"last",
- (getter)Noddy_getlast, (setter)Noddy_setlast,
- "last name",
- NULL},
- {NULL} /* Sentinel */
-};
-\end{verbatim}
-
-and register it in the \member{tp_getset} slot:
-
-\begin{verbatim}
- Noddy_getseters, /* tp_getset */
-\end{verbatim}
-
-to register out attribute getters and setters.
-
-The last item in a \ctype{PyGetSetDef} structure is the closure
-mentioned above. In this case, we aren't using the closure, so we just
-pass \NULL.
-
-We also remove the member definitions for these attributes:
-
-\begin{verbatim}
-static PyMemberDef Noddy_members[] = {
- {"number", T_INT, offsetof(Noddy, number), 0,
- "noddy number"},
- {NULL} /* Sentinel */
-};
-\end{verbatim}
-
-With these changes, we can assure that the \member{first} and
-\member{last} members are never NULL so we can remove checks for \NULL
-values in almost all cases. This means that most of the
-\cfunction{Py_XDECREF} calls can be converted to \cfunction{Py_DECREF}
-calls. The only place we can't change these calls is in the
-deallocator, where there is the possibility that the initialization of
-these members failed in the constructor.
-
-We also rename the module initialization function and module name in
-the initialization function, as we did before, and we add an extra
-definition to the \file{setup.py} file.
-
-\section{Type Methods
- \label{dnt-type-methods}}
-
-This section aims to give a quick fly-by on the various type methods
-you can implement and what they do.
-
-Here is the definition of \ctype{PyTypeObject}, with some fields only
-used in debug builds omitted:
-
-\verbatiminput{typestruct.h}
-
-Now that's a \emph{lot} of methods. Don't worry too much though - if
-you have a type you want to define, the chances are very good that you
-will only implement a handful of these.
-
-As you probably expect by now, we're going to go over this and give
-more information about the various handlers. We won't go in the order
-they are defined in the structure, because there is a lot of
-historical baggage that impacts the ordering of the fields; be sure
-your type initializaion keeps the fields in the right order! It's
-often easiest to find an example that includes all the fields you need
-(even if they're initialized to \code{0}) and then change the values
-to suit your new type.
-
-\begin{verbatim}
- char *tp_name; /* For printing */
-\end{verbatim}
-
-The name of the type - as mentioned in the last section, this will
-appear in various places, almost entirely for diagnostic purposes.
-Try to choose something that will be helpful in such a situation!
-
-\begin{verbatim}
- int tp_basicsize, tp_itemsize; /* For allocation */
-\end{verbatim}
-
-These fields tell the runtime how much memory to allocate when new
-objects of this type are created. Python has some builtin support
-for variable length structures (think: strings, lists) which is where
-the \member{tp_itemsize} field comes in. This will be dealt with
-later.
-
-\begin{verbatim}
- char *tp_doc;
-\end{verbatim}
-
-Here you can put a string (or its address) that you want returned when
-the Python script references \code{obj.__doc__} to retrieve the
-docstring.
-
-Now we come to the basic type methods---the ones most extension types
-will implement.
-
-
-\subsection{Finalization and De-allocation}
-
-\index{object!deallocation}
-\index{deallocation, object}
-\index{object!finalization}
-\index{finalization, of objects}
-
-\begin{verbatim}
- destructor tp_dealloc;
-\end{verbatim}
-
-This function is called when the reference count of the instance of
-your type is reduced to zero and the Python interpreter wants to
-reclaim it. If your type has memory to free or other clean-up to
-perform, put it here. The object itself needs to be freed here as
-well. Here is an example of this function:
-
-\begin{verbatim}
-static void
-newdatatype_dealloc(newdatatypeobject * obj)
-{
- free(obj->obj_UnderlyingDatatypePtr);
- obj->ob_type->tp_free(obj);
-}
-\end{verbatim}
-
-One important requirement of the deallocator function is that it
-leaves any pending exceptions alone. This is important since
-deallocators are frequently called as the interpreter unwinds the
-Python stack; when the stack is unwound due to an exception (rather
-than normal returns), nothing is done to protect the deallocators from
-seeing that an exception has already been set. Any actions which a
-deallocator performs which may cause additional Python code to be
-executed may detect that an exception has been set. This can lead to
-misleading errors from the interpreter. The proper way to protect
-against this is to save a pending exception before performing the
-unsafe action, and restoring it when done. This can be done using the
-\cfunction{PyErr_Fetch()}\ttindex{PyErr_Fetch()} and
-\cfunction{PyErr_Restore()}\ttindex{PyErr_Restore()} functions:
-
-\begin{verbatim}
-static void
-my_dealloc(PyObject *obj)
-{
- MyObject *self = (MyObject *) obj;
- PyObject *cbresult;
-
- if (self->my_callback != NULL) {
- PyObject *err_type, *err_value, *err_traceback;
- int have_error = PyErr_Occurred() ? 1 : 0;
-
- if (have_error)
- PyErr_Fetch(&err_type, &err_value, &err_traceback);
-
- cbresult = PyObject_CallObject(self->my_callback, NULL);
- if (cbresult == NULL)
- PyErr_WriteUnraisable();
- else
- Py_DECREF(cbresult);
-
- if (have_error)
- PyErr_Restore(err_type, err_value, err_traceback);
-
- Py_DECREF(self->my_callback);
- }
- obj->ob_type->tp_free((PyObject*)self);
-}
-\end{verbatim}
-
-
-\subsection{Object Presentation}
-
-In Python, there are three ways to generate a textual representation
-of an object: the \function{repr()}\bifuncindex{repr} function (or
-equivalent backtick syntax), the \function{str()}\bifuncindex{str}
-function, and the \keyword{print} statement. For most objects, the
-\keyword{print} statement is equivalent to the \function{str()}
-function, but it is possible to special-case printing to a
-\ctype{FILE*} if necessary; this should only be done if efficiency is
-identified as a problem and profiling suggests that creating a
-temporary string object to be written to a file is too expensive.
-
-These handlers are all optional, and most types at most need to
-implement the \member{tp_str} and \member{tp_repr} handlers.
-
-\begin{verbatim}
- reprfunc tp_repr;
- reprfunc tp_str;
- printfunc tp_print;
-\end{verbatim}
-
-The \member{tp_repr} handler should return a string object containing
-a representation of the instance for which it is called. Here is a
-simple example:
-
-\begin{verbatim}
-static PyObject *
-newdatatype_repr(newdatatypeobject * obj)
-{
- return PyString_FromFormat("Repr-ified_newdatatype{{size:\%d}}",
- obj->obj_UnderlyingDatatypePtr->size);
-}
-\end{verbatim}
-
-If no \member{tp_repr} handler is specified, the interpreter will
-supply a representation that uses the type's \member{tp_name} and a
-uniquely-identifying value for the object.
-
-The \member{tp_str} handler is to \function{str()} what the
-\member{tp_repr} handler described above is to \function{repr()}; that
-is, it is called when Python code calls \function{str()} on an
-instance of your object. Its implementation is very similar to the
-\member{tp_repr} function, but the resulting string is intended for
-human consumption. If \member{tp_str} is not specified, the
-\member{tp_repr} handler is used instead.
-
-Here is a simple example:
-
-\begin{verbatim}
-static PyObject *
-newdatatype_str(newdatatypeobject * obj)
-{
- return PyString_FromFormat("Stringified_newdatatype{{size:\%d}}",
- obj->obj_UnderlyingDatatypePtr->size);
-}
-\end{verbatim}
-
-The print function will be called whenever Python needs to "print" an
-instance of the type. For example, if 'node' is an instance of type
-TreeNode, then the print function is called when Python code calls:
-
-\begin{verbatim}
-print node
-\end{verbatim}
-
-There is a flags argument and one flag, \constant{Py_PRINT_RAW}, and
-it suggests that you print without string quotes and possibly without
-interpreting escape sequences.
-
-The print function receives a file object as an argument. You will
-likely want to write to that file object.
-
-Here is a sampe print function:
-
-\begin{verbatim}
-static int
-newdatatype_print(newdatatypeobject *obj, FILE *fp, int flags)
-{
- if (flags & Py_PRINT_RAW) {
- fprintf(fp, "<{newdatatype object--size: %d}>",
- obj->obj_UnderlyingDatatypePtr->size);
- }
- else {
- fprintf(fp, "\"<{newdatatype object--size: %d}>\"",
- obj->obj_UnderlyingDatatypePtr->size);
- }
- return 0;
-}
-\end{verbatim}
-
-
-\subsection{Attribute Management}
-
-For every object which can support attributes, the corresponding type
-must provide the functions that control how the attributes are
-resolved. There needs to be a function which can retrieve attributes
-(if any are defined), and another to set attributes (if setting
-attributes is allowed). Removing an attribute is a special case, for
-which the new value passed to the handler is \NULL.
-
-Python supports two pairs of attribute handlers; a type that supports
-attributes only needs to implement the functions for one pair. The
-difference is that one pair takes the name of the attribute as a
-\ctype{char*}, while the other accepts a \ctype{PyObject*}. Each type
-can use whichever pair makes more sense for the implementation's
-convenience.
-
-\begin{verbatim}
- getattrfunc tp_getattr; /* char * version */
- setattrfunc tp_setattr;
- /* ... */
- getattrofunc tp_getattrofunc; /* PyObject * version */
- setattrofunc tp_setattrofunc;
-\end{verbatim}
-
-If accessing attributes of an object is always a simple operation
-(this will be explained shortly), there are generic implementations
-which can be used to provide the \ctype{PyObject*} version of the
-attribute management functions. The actual need for type-specific
-attribute handlers almost completely disappeared starting with Python
-2.2, though there are many examples which have not been updated to use
-some of the new generic mechanism that is available.
-
-
-\subsubsection{Generic Attribute Management}
-
-\versionadded{2.2}
-
-Most extension types only use \emph{simple} attributes. So, what
-makes the attributes simple? There are only a couple of conditions
-that must be met:
-
-\begin{enumerate}
- \item The name of the attributes must be known when
- \cfunction{PyType_Ready()} is called.
-
- \item No special processing is needed to record that an attribute
- was looked up or set, nor do actions need to be taken based
- on the value.
-\end{enumerate}
-
-Note that this list does not place any restrictions on the values of
-the attributes, when the values are computed, or how relevant data is
-stored.
-
-When \cfunction{PyType_Ready()} is called, it uses three tables
-referenced by the type object to create \emph{descriptors} which are
-placed in the dictionary of the type object. Each descriptor controls
-access to one attribute of the instance object. Each of the tables is
-optional; if all three are \NULL, instances of the type will only have
-attributes that are inherited from their base type, and should leave
-the \member{tp_getattro} and \member{tp_setattro} fields \NULL{} as
-well, allowing the base type to handle attributes.
-
-The tables are declared as three fields of the type object:
-
-\begin{verbatim}
- struct PyMethodDef *tp_methods;
- struct PyMemberDef *tp_members;
- struct PyGetSetDef *tp_getset;
-\end{verbatim}
-
-If \member{tp_methods} is not \NULL, it must refer to an array of
-\ctype{PyMethodDef} structures. Each entry in the table is an
-instance of this structure:
-
-\begin{verbatim}
-typedef struct PyMethodDef {
- char *ml_name; /* method name */
- PyCFunction ml_meth; /* implementation function */
- int ml_flags; /* flags */
- char *ml_doc; /* docstring */
-} PyMethodDef;
-\end{verbatim}
-
-One entry should be defined for each method provided by the type; no
-entries are needed for methods inherited from a base type. One
-additional entry is needed at the end; it is a sentinel that marks the
-end of the array. The \member{ml_name} field of the sentinel must be
-\NULL.
-
-XXX Need to refer to some unified discussion of the structure fields,
-shared with the next section.
-
-The second table is used to define attributes which map directly to
-data stored in the instance. A variety of primitive C types are
-supported, and access may be read-only or read-write. The structures
-in the table are defined as:
-
-\begin{verbatim}
-typedef struct PyMemberDef {
- char *name;
- int type;
- int offset;
- int flags;
- char *doc;
-} PyMemberDef;
-\end{verbatim}
-
-For each entry in the table, a descriptor will be constructed and
-added to the type which will be able to extract a value from the
-instance structure. The \member{type} field should contain one of the
-type codes defined in the \file{structmember.h} header; the value will
-be used to determine how to convert Python values to and from C
-values. The \member{flags} field is used to store flags which control
-how the attribute can be accessed.
-
-XXX Need to move some of this to a shared section!
-
-The following flag constants are defined in \file{structmember.h};
-they may be combined using bitwise-OR.
-
-\begin{tableii}{l|l}{constant}{Constant}{Meaning}
- \lineii{READONLY \ttindex{READONLY}}
- {Never writable.}
- \lineii{RO \ttindex{RO}}
- {Shorthand for \constant{READONLY}.}
- \lineii{READ_RESTRICTED \ttindex{READ_RESTRICTED}}
- {Not readable in restricted mode.}
- \lineii{WRITE_RESTRICTED \ttindex{WRITE_RESTRICTED}}
- {Not writable in restricted mode.}
- \lineii{RESTRICTED \ttindex{RESTRICTED}}
- {Not readable or writable in restricted mode.}
-\end{tableii}
-
-An interesting advantage of using the \member{tp_members} table to
-build descriptors that are used at runtime is that any attribute
-defined this way can have an associated docstring simply by providing
-the text in the table. An application can use the introspection API
-to retrieve the descriptor from the class object, and get the
-docstring using its \member{__doc__} attribute.
-
-As with the \member{tp_methods} table, a sentinel entry with a
-\member{name} value of \NULL{} is required.
-
-
-% XXX Descriptors need to be explained in more detail somewhere, but
-% not here.
-%
-% Descriptor objects have two handler functions which correspond to
-% the \member{tp_getattro} and \member{tp_setattro} handlers. The
-% \method{__get__()} handler is a function which is passed the
-% descriptor, instance, and type objects, and returns the value of the
-% attribute, or it returns \NULL{} and sets an exception. The
-% \method{__set__()} handler is passed the descriptor, instance, type,
-% and new value;
-
-
-\subsubsection{Type-specific Attribute Management}
-
-For simplicity, only the \ctype{char*} version will be demonstrated
-here; the type of the name parameter is the only difference between
-the \ctype{char*} and \ctype{PyObject*} flavors of the interface.
-This example effectively does the same thing as the generic example
-above, but does not use the generic support added in Python 2.2. The
-value in showing this is two-fold: it demonstrates how basic attribute
-management can be done in a way that is portable to older versions of
-Python, and explains how the handler functions are called, so that if
-you do need to extend their functionality, you'll understand what
-needs to be done.
-
-The \member{tp_getattr} handler is called when the object requires an
-attribute look-up. It is called in the same situations where the
-\method{__getattr__()} method of a class would be called.
-
-A likely way to handle this is (1) to implement a set of functions
-(such as \cfunction{newdatatype_getSize()} and
-\cfunction{newdatatype_setSize()} in the example below), (2) provide a
-method table listing these functions, and (3) provide a getattr
-function that returns the result of a lookup in that table. The
-method table uses the same structure as the \member{tp_methods} field
-of the type object.
-
-Here is an example:
-
-\begin{verbatim}
-static PyMethodDef newdatatype_methods[] = {
- {"getSize", (PyCFunction)newdatatype_getSize, METH_VARARGS,
- "Return the current size."},
- {"setSize", (PyCFunction)newdatatype_setSize, METH_VARARGS,
- "Set the size."},
- {NULL, NULL, 0, NULL} /* sentinel */
-};
-
-static PyObject *
-newdatatype_getattr(newdatatypeobject *obj, char *name)
-{
- return Py_FindMethod(newdatatype_methods, (PyObject *)obj, name);
-}
-\end{verbatim}
-
-The \member{tp_setattr} handler is called when the
-\method{__setattr__()} or \method{__delattr__()} method of a class
-instance would be called. When an attribute should be deleted, the
-third parameter will be \NULL. Here is an example that simply raises
-an exception; if this were really all you wanted, the
-\member{tp_setattr} handler should be set to \NULL.
-
-\begin{verbatim}
-static int
-newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
-{
- (void)PyErr_Format(PyExc_RuntimeError, "Read-only attribute: \%s", name);
- return -1;
-}
-\end{verbatim}
-
-
-\subsection{Object Comparison}
-
-\begin{verbatim}
- cmpfunc tp_compare;
-\end{verbatim}
-
-The \member{tp_compare} handler is called when comparisons are needed
-and the object does not implement the specific rich comparison method
-which matches the requested comparison. (It is always used if defined
-and the \cfunction{PyObject_Compare()} or \cfunction{PyObject_Cmp()}
-functions are used, or if \function{cmp()} is used from Python.)
-It is analogous to the \method{__cmp__()} method. This function
-should return \code{-1} if \var{obj1} is less than
-\var{obj2}, \code{0} if they are equal, and \code{1} if
-\var{obj1} is greater than
-\var{obj2}.
-(It was previously allowed to return arbitrary negative or positive
-integers for less than and greater than, respectively; as of Python
-2.2, this is no longer allowed. In the future, other return values
-may be assigned a different meaning.)
-
-A \member{tp_compare} handler may raise an exception. In this case it
-should return a negative value. The caller has to test for the
-exception using \cfunction{PyErr_Occurred()}.
-
-
-Here is a sample implementation:
-
-\begin{verbatim}
-static int
-newdatatype_compare(newdatatypeobject * obj1, newdatatypeobject * obj2)
-{
- long result;
-
- if (obj1->obj_UnderlyingDatatypePtr->size <
- obj2->obj_UnderlyingDatatypePtr->size) {
- result = -1;
- }
- else if (obj1->obj_UnderlyingDatatypePtr->size >
- obj2->obj_UnderlyingDatatypePtr->size) {
- result = 1;
- }
- else {
- result = 0;
- }
- return result;
-}
-\end{verbatim}
-
-
-\subsection{Abstract Protocol Support}
-
-Python supports a variety of \emph{abstract} `protocols;' the specific
-interfaces provided to use these interfaces are documented in the
-\citetitle[../api/api.html]{Python/C API Reference Manual} in the
-chapter ``\ulink{Abstract Objects Layer}{../api/abstract.html}.''
-
-A number of these abstract interfaces were defined early in the
-development of the Python implementation. In particular, the number,
-mapping, and sequence protocols have been part of Python since the
-beginning. Other protocols have been added over time. For protocols
-which depend on several handler routines from the type implementation,
-the older protocols have been defined as optional blocks of handlers
-referenced by the type object. For newer protocols there are
-additional slots in the main type object, with a flag bit being set to
-indicate that the slots are present and should be checked by the
-interpreter. (The flag bit does not indicate that the slot values are
-non-\NULL. The flag may be set to indicate the presense of a slot,
-but a slot may still be unfilled.)
-
-\begin{verbatim}
- PyNumberMethods tp_as_number;
- PySequenceMethods tp_as_sequence;
- PyMappingMethods tp_as_mapping;
-\end{verbatim}
-
-If you wish your object to be able to act like a number, a sequence,
-or a mapping object, then you place the address of a structure that
-implements the C type \ctype{PyNumberMethods},
-\ctype{PySequenceMethods}, or \ctype{PyMappingMethods}, respectively.
-It is up to you to fill in this structure with appropriate values. You
-can find examples of the use of each of these in the \file{Objects}
-directory of the Python source distribution.
-
-
-\begin{verbatim}
- hashfunc tp_hash;
-\end{verbatim}
-
-This function, if you choose to provide it, should return a hash
-number for an instance of your datatype. Here is a moderately
-pointless example:
-
-\begin{verbatim}
-static long
-newdatatype_hash(newdatatypeobject *obj)
-{
- long result;
- result = obj->obj_UnderlyingDatatypePtr->size;
- result = result * 3;
- return result;
-}
-\end{verbatim}
-
-\begin{verbatim}
- ternaryfunc tp_call;
-\end{verbatim}
-
-This function is called when an instance of your datatype is "called",
-for example, if \code{obj1} is an instance of your datatype and the Python
-script contains \code{obj1('hello')}, the \member{tp_call} handler is
-invoked.
-
-This function takes three arguments:
-
-\begin{enumerate}
- \item
- \var{arg1} is the instance of the datatype which is the subject of
- the call. If the call is \code{obj1('hello')}, then \var{arg1} is
- \code{obj1}.
-
- \item
- \var{arg2} is a tuple containing the arguments to the call. You
- can use \cfunction{PyArg_ParseTuple()} to extract the arguments.
-
- \item
- \var{arg3} is a dictionary of keyword arguments that were passed.
- If this is non-\NULL{} and you support keyword arguments, use
- \cfunction{PyArg_ParseTupleAndKeywords()} to extract the
- arguments. If you do not want to support keyword arguments and
- this is non-\NULL, raise a \exception{TypeError} with a message
- saying that keyword arguments are not supported.
-\end{enumerate}
-
-Here is a desultory example of the implementation of the call function.
-
-\begin{verbatim}
-/* Implement the call function.
- * obj1 is the instance receiving the call.
- * obj2 is a tuple containing the arguments to the call, in this
- * case 3 strings.
- */
-static PyObject *
-newdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *other)
-{
- PyObject *result;
- char *arg1;
- char *arg2;
- char *arg3;
-
- if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) {
- return NULL;
- }
- result = PyString_FromFormat(
- "Returning -- value: [\%d] arg1: [\%s] arg2: [\%s] arg3: [\%s]\n",
- obj->obj_UnderlyingDatatypePtr->size,
- arg1, arg2, arg3);
- printf("\%s", PyString_AS_STRING(result));
- return result;
-}
-\end{verbatim}
-
-XXX some fields need to be added here...
-
-
-\begin{verbatim}
- /* Added in release 2.2 */
- /* Iterators */
- getiterfunc tp_iter;
- iternextfunc tp_iternext;
-\end{verbatim}
-
-These functions provide support for the iterator protocol. Any object
-which wishes to support iteration over its contents (which may be
-generated during iteration) must implement the \code{tp_iter}
-handler. Objects which are returned by a \code{tp_iter} handler must
-implement both the \code{tp_iter} and \code{tp_iternext} handlers.
-Both handlers take exactly one parameter, the instance for which they
-are being called, and return a new reference. In the case of an
-error, they should set an exception and return \NULL.
-
-For an object which represents an iterable collection, the
-\code{tp_iter} handler must return an iterator object. The iterator
-object is responsible for maintaining the state of the iteration. For
-collections which can support multiple iterators which do not
-interfere with each other (as lists and tuples do), a new iterator
-should be created and returned. Objects which can only be iterated
-over once (usually due to side effects of iteration) should implement
-this handler by returning a new reference to themselves, and should
-also implement the \code{tp_iternext} handler. File objects are an
-example of such an iterator.
-
-Iterator objects should implement both handlers. The \code{tp_iter}
-handler should return a new reference to the iterator (this is the
-same as the \code{tp_iter} handler for objects which can only be
-iterated over destructively). The \code{tp_iternext} handler should
-return a new reference to the next object in the iteration if there is
-one. If the iteration has reached the end, it may return \NULL{}
-without setting an exception or it may set \exception{StopIteration};
-avoiding the exception can yield slightly better performance. If an
-actual error occurs, it should set an exception and return \NULL.
-
-
-\subsection{Supporting the Cycle Collector
- \label{example-cycle-support}}
-
-This example shows only enough of the implementation of an extension
-type to show how the garbage collector support needs to be added. It
-shows the definition of the object structure, the
-\member{tp_traverse}, \member{tp_clear} and \member{tp_dealloc}
-implementations, the type structure, and a constructor --- the module
-initialization needed to export the constructor to Python is not shown
-as there are no special considerations there for the collector. To
-make this interesting, assume that the module exposes ways for the
-\member{container} field of the object to be modified. Note that
-since no checks are made on the type of the object used to initialize
-\member{container}, we have to assume that it may be a container.
-
-\verbatiminput{cycle-gc.c}
-
-Full details on the APIs related to the cycle detector are in
-\ulink{Supporting Cyclic Garbarge
-Collection}{../api/supporting-cycle-detection.html} in the
-\citetitle[../api/api.html]{Python/C API Reference Manual}.
-
-
-\subsection{More Suggestions}
-
-Remember that you can omit most of these functions, in which case you
-provide \code{0} as a value. There are type definitions for each of
-the functions you must provide. They are in \file{object.h} in the
-Python include directory that comes with the source distribution of
-Python.
-
-In order to learn how to implement any specific method for your new
-datatype, do the following: Download and unpack the Python source
-distribution. Go the the \file{Objects} directory, then search the
-C source files for \code{tp_} plus the function you want (for
-example, \code{tp_print} or \code{tp_compare}). You will find
-examples of the function you want to implement.
-
-When you need to verify that an object is an instance of the type
-you are implementing, use the \cfunction{PyObject_TypeCheck} function.
-A sample of its use might be something like the following:
-
-\begin{verbatim}
- if (! PyObject_TypeCheck(some_object, &MyType)) {
- PyErr_SetString(PyExc_TypeError, "arg #1 not a mything");
- return NULL;
- }
-\end{verbatim}
diff --git a/Doc/ext/noddy.c b/Doc/ext/noddy.c
deleted file mode 100644
index 632d8e1559..0000000000
--- a/Doc/ext/noddy.c
+++ /dev/null
@@ -1,70 +0,0 @@
-#include
-
-typedef struct {
- PyObject_HEAD
- /* Type-specific fields go here. */
-} noddy_NoddyObject;
-
-static PyTypeObject noddy_NoddyType = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "noddy.Noddy", /*tp_name*/
- sizeof(noddy_NoddyObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- 0, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Noddy objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
-};
-
-static PyMethodDef noddy_methods[] = {
- {NULL} /* Sentinel */
-};
-
-#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
-#define PyMODINIT_FUNC void
-#endif
-PyMODINIT_FUNC
-initnoddy(void)
-{
- PyObject* m;
-
- if (PyType_Ready(&noddy_NoddyType) < 0)
- return;
-
- m = Py_InitModule3("noddy", noddy_methods,
- "Example module that creates an extension type.");
-
- Py_INCREF(&noddy_NoddyType);
- PyModule_AddObject(m, "Noddy", (PyObject *)&noddy_NoddyType);
-}
diff --git a/Doc/ext/noddy2.c b/Doc/ext/noddy2.c
deleted file mode 100644
index fcce2abd97..0000000000
--- a/Doc/ext/noddy2.c
+++ /dev/null
@@ -1,189 +0,0 @@
-#include
-#include "structmember.h"
-
-typedef struct {
- PyObject_HEAD
- PyObject *first;
- PyObject *last;
- int number;
-} Noddy;
-
-static void
-Noddy_dealloc(Noddy* self)
-{
- Py_XDECREF(self->first);
- Py_XDECREF(self->last);
- self->ob_type->tp_free((PyObject*)self);
-}
-
-static PyObject *
-Noddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
- Noddy *self;
-
- self = (Noddy *)type->tp_alloc(type, 0);
- if (self != NULL) {
- self->first = PyString_FromString("");
- if (self->first == NULL)
- {
- Py_DECREF(self);
- return NULL;
- }
-
- self->last = PyString_FromString("");
- if (self->last == NULL)
- {
- Py_DECREF(self);
- return NULL;
- }
-
- self->number = 0;
- }
-
- return (PyObject *)self;
-}
-
-static PyObject *
-Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
-{
- PyObject *first=NULL, *last=NULL;
-
- static char *kwlist[] = {"first", "last", "number", NULL};
-
- if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
- &first, &last,
- &self->number))
- return NULL;
-
- if (first) {
- Py_XDECREF(self->first);
- Py_INCREF(first);
- self->first = first;
- }
-
- if (last) {
- Py_XDECREF(self->last);
- Py_INCREF(last);
- self->last = last;
- }
-
- Py_INCREF(Py_None);
- return Py_None;
-}
-
-
-static PyMemberDef Noddy_members[] = {
- {"first", T_OBJECT_EX, offsetof(Noddy, first), 0,
- "first name"},
- {"last", T_OBJECT_EX, offsetof(Noddy, last), 0,
- "last name"},
- {"number", T_INT, offsetof(Noddy, number), 0,
- "noddy number"},
- {NULL} /* Sentinel */
-};
-
-static PyObject *
-Noddy_name(Noddy* self)
-{
- static PyObject *format = NULL;
- PyObject *args, *result;
-
- if (format == NULL) {
- format = PyString_FromString("%s %s");
- if (format == NULL)
- return NULL;
- }
-
- if (self->first == NULL) {
- PyErr_SetString(PyExc_AttributeError, "first");
- return NULL;
- }
-
- if (self->last == NULL) {
- PyErr_SetString(PyExc_AttributeError, "last");
- return NULL;
- }
-
- args = Py_BuildValue("OO", self->first, self->last);
- if (args == NULL)
- return NULL;
-
- result = PyString_Format(format, args);
- Py_DECREF(args);
-
- return result;
-}
-
-static PyMethodDef Noddy_methods[] = {
- {"name", (PyCFunction)Noddy_name, METH_NOARGS,
- "Return the name, combining the first and last name"
- },
- {NULL} /* Sentinel */
-};
-
-static PyTypeObject NoddyType = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "noddy.Noddy", /*tp_name*/
- sizeof(Noddy), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Noddy_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
- "Noddy objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- Noddy_methods, /* tp_methods */
- Noddy_members, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Noddy_init, /* tp_init */
- 0, /* tp_alloc */
- Noddy_new, /* tp_new */
-};
-
-static PyMethodDef module_methods[] = {
- {NULL} /* Sentinel */
-};
-
-#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
-#define PyMODINIT_FUNC void
-#endif
-PyMODINIT_FUNC
-initnoddy2(void)
-{
- PyObject* m;
-
- if (PyType_Ready(&NoddyType) < 0)
- return;
-
- m = Py_InitModule3("noddy2", module_methods,
- "Example module that creates an extension type.");
-
- if (m == NULL)
- return;
-
- Py_INCREF(&NoddyType);
- PyModule_AddObject(m, "Noddy", (PyObject *)&NoddyType);
-}
diff --git a/Doc/ext/noddy3.c b/Doc/ext/noddy3.c
deleted file mode 100644
index 08ac31ec6a..0000000000
--- a/Doc/ext/noddy3.c
+++ /dev/null
@@ -1,242 +0,0 @@
-#include
-#include "structmember.h"
-
-typedef struct {
- PyObject_HEAD
- PyObject *first;
- PyObject *last;
- int number;
-} Noddy;
-
-static void
-Noddy_dealloc(Noddy* self)
-{
- Py_XDECREF(self->first);
- Py_XDECREF(self->last);
- self->ob_type->tp_free((PyObject*)self);
-}
-
-static PyObject *
-Noddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
-{
- Noddy *self;
-
- self = (Noddy *)type->tp_alloc(type, 0);
- if (self != NULL) {
- self->first = PyString_FromString("");
- if (self->first == NULL)
- {
- Py_DECREF(self);
- return NULL;
- }
-
- self->last = PyString_FromString("");
- if (self->last == NULL)
- {
- Py_DECREF(self);
- return NULL;
- }
-
- self->number = 0;
- }
-
- return (PyObject *)self;
-}
-
-static PyObject *
-Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
-{
- PyObject *first=NULL, *last=NULL;
-
- static char *kwlist[] = {"first", "last", "number", NULL};
-
- if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
- &first, &last,
- &self->number))
- return NULL;
-
- if (first) {
- Py_DECREF(self->first);
- Py_INCREF(first);
- self->first = first;
- }
-
- if (last) {
- Py_DECREF(self->last);
- Py_INCREF(last);
- self->last = last;
- }
-
- Py_INCREF(Py_None);
- return Py_None;
-}
-
-static PyMemberDef Noddy_members[] = {
- {"number", T_INT, offsetof(Noddy, number), 0,
- "noddy number"},
- {NULL} /* Sentinel */
-};
-
-static PyObject *
-Noddy_getfirst(Noddy *self, void *closure)
-{
- Py_INCREF(self->first);
- return self->first;
-}
-
-static int
-Noddy_setfirst(Noddy *self, PyObject *value, void *closure)
-{
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
- return -1;
- }
-
- if (! PyString_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "The first attribute value must be a string");
- return -1;
- }
-
- Py_DECREF(self->first);
- Py_INCREF(value);
- self->first = value;
-
- return 0;
-}
-
-static PyObject *
-Noddy_getlast(Noddy *self, void *closure)
-{
- Py_INCREF(self->last);
- return self->last;
-}
-
-static int
-Noddy_setlast(Noddy *self, PyObject *value, void *closure)
-{
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
- return -1;
- }
-
- if (! PyString_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "The last attribute value must be a string");
- return -1;
- }
-
- Py_DECREF(self->last);
- Py_INCREF(value);
- self->last = value;
-
- return 0;
-}
-
-static PyGetSetDef Noddy_getseters[] = {
- {"first",
- (getter)Noddy_getfirst, (setter)Noddy_setfirst,
- "first name",
- NULL},
- {"last",
- (getter)Noddy_getlast, (setter)Noddy_setlast,
- "last name",
- NULL},
- {NULL} /* Sentinel */
-};
-
-static PyObject *
-Noddy_name(Noddy* self)
-{
- static PyObject *format = NULL;
- PyObject *args, *result;
-
- if (format == NULL) {
- format = PyString_FromString("%s %s");
- if (format == NULL)
- return NULL;
- }
-
- args = Py_BuildValue("OO", self->first, self->last);
- if (args == NULL)
- return NULL;
-
- result = PyString_Format(format, args);
- Py_DECREF(args);
-
- return result;
-}
-
-static PyMethodDef Noddy_methods[] = {
- {"name", (PyCFunction)Noddy_name, METH_NOARGS,
- "Return the name, combining the first and last name"
- },
- {NULL} /* Sentinel */
-};
-
-static PyTypeObject NoddyType = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "noddy.Noddy", /*tp_name*/
- sizeof(Noddy), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)Noddy_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
- 0, /*tp_call*/
- 0, /*tp_str*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
- "Noddy objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- Noddy_methods, /* tp_methods */
- Noddy_members, /* tp_members */
- Noddy_getseters, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Noddy_init, /* tp_init */
- 0, /* tp_alloc */
- Noddy_new, /* tp_new */
-};
-
-static PyMethodDef module_methods[] = {
- {NULL} /* Sentinel */
-};
-
-#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
-#define PyMODINIT_FUNC void
-#endif
-PyMODINIT_FUNC
-initnoddy3(void)
-{
- PyObject* m;
-
- if (PyType_Ready(&NoddyType) < 0)
- return;
-
- m = Py_InitModule3("noddy3", module_methods,
- "Example module that creates an extension type.");
-
- if (m == NULL)
- return;
-
- Py_INCREF(&NoddyType);
- PyModule_AddObject(m, "Noddy", (PyObject *)&NoddyType);
-}
diff --git a/Doc/ext/run-func.c b/Doc/ext/run-func.c
deleted file mode 100644
index b5be5c6bf4..0000000000
--- a/Doc/ext/run-func.c
+++ /dev/null
@@ -1,70 +0,0 @@
-#include
-
-int
-main(int argc, char *argv[])
-{
- PyObject *pName, *pModule, *pDict, *pFunc;
- PyObject *pArgs, *pValue;
- int i;
-
- if (argc < 3) {
- fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
- return 1;
- }
-
- Py_Initialize();
- pName = PyString_FromString(argv[1]);
- /* Error checking of pName left out */
-
- pModule = PyImport_Import(pName);
- Py_DECREF(pName);
-
- if (pModule != NULL) {
- pDict = PyModule_GetDict(pModule);
- /* pDict is a borrowed reference */
-
- pFunc = PyDict_GetItemString(pDict, argv[2]);
- /* pFun: Borrowed reference */
-
- if (pFunc && PyCallable_Check(pFunc)) {
- pArgs = PyTuple_New(argc - 3);
- for (i = 0; i < argc - 3; ++i) {
- pValue = PyInt_FromLong(atoi(argv[i + 3]));
- if (!pValue) {
- Py_DECREF(pArgs);
- Py_DECREF(pModule);
- fprintf(stderr, "Cannot convert argument\n");
- return 1;
- }
- /* pValue reference stolen here: */
- PyTuple_SetItem(pArgs, i, pValue);
- }
- pValue = PyObject_CallObject(pFunc, pArgs);
- Py_DECREF(pArgs);
- if (pValue != NULL) {
- printf("Result of call: %ld\n", PyInt_AsLong(pValue));
- Py_DECREF(pValue);
- }
- else {
- Py_DECREF(pModule);
- PyErr_Print();
- fprintf(stderr,"Call failed\n");
- return 1;
- }
- /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */
- }
- else {
- if (PyErr_Occurred())
- PyErr_Print();
- fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
- }
- Py_DECREF(pModule);
- }
- else {
- PyErr_Print();
- fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
- return 1;
- }
- Py_Finalize();
- return 0;
-}
diff --git a/Doc/ext/windows.tex b/Doc/ext/windows.tex
deleted file mode 100644
index 69d0cd99ba..0000000000
--- a/Doc/ext/windows.tex
+++ /dev/null
@@ -1,317 +0,0 @@
-\chapter{Building C and \Cpp{} Extensions on Windows%
- \label{building-on-windows}}
-
-
-This chapter briefly explains how to create a Windows extension module
-for Python using Microsoft Visual \Cpp, and follows with more
-detailed background information on how it works. The explanatory
-material is useful for both the Windows programmer learning to build
-Python extensions and the \UNIX{} programmer interested in producing
-software which can be successfully built on both \UNIX{} and Windows.
-
-Module authors are encouraged to use the distutils approach for
-building extension modules, instead of the one described in this
-section. You will still need the C compiler that was used to build
-Python; typically Microsoft Visual \Cpp.
-
-\begin{notice}
- This chapter mentions a number of filenames that include an encoded
- Python version number. These filenames are represented with the
- version number shown as \samp{XY}; in practive, \character{X} will
- be the major version number and \character{Y} will be the minor
- version number of the Python release you're working with. For
- example, if you are using Python 2.2.1, \samp{XY} will actually be
- \samp{22}.
-\end{notice}
-
-
-\section{A Cookbook Approach \label{win-cookbook}}
-
-There are two approaches to building extension modules on Windows,
-just as there are on \UNIX: use the \refmodule{distutils} package to
-control the build process, or do things manually. The distutils
-approach works well for most extensions; documentation on using
-\refmodule{distutils} to build and package extension modules is
-available in \citetitle[../dist/dist.html]{Distributing Python
-Modules}. This section describes the manual approach to building
-Python extensions written in C or \Cpp.
-
-To build extensions using these instructions, you need to have a copy
-of the Python sources of the same version as your installed Python.
-You will need Microsoft Visual \Cpp{} ``Developer Studio''; project
-files are supplied for V\Cpp{} version 6, but you can use older
-versions of V\Cpp. The example files described here are distributed
-with the Python sources in the \file{PC\textbackslash
-example_nt\textbackslash} directory.
-
-\begin{enumerate}
- \item
- \strong{Copy the example files}\\
- The \file{example_nt} directory is a subdirectory of the \file{PC}
- directory, in order to keep all the PC-specific files under the
- same directory in the source distribution. However, the
- \file{example_nt} directory can't actually be used from this
- location. You first need to copy or move it up one level, so that
- \file{example_nt} is a sibling of the \file{PC} and \file{Include}
- directories. Do all your work from within this new location.
-
- \item
- \strong{Open the project}\\
- From V\Cpp, use the \menuselection{File \sub Open Workspace}
- dialog (not \menuselection{File \sub Open}!). Navigate to and
- select the file \file{example.dsw}, in the \emph{copy} of the
- \file{example_nt} directory you made above. Click Open.
-
- \item
- \strong{Build the example DLL}\\
- In order to check that everything is set up right, try building:
-
- \begin{enumerate}
- \item
- Select a configuration. This step is optional. Choose
- \menuselection{Build \sub Select Active Configuration} and
- select either ``example - Win32 Release'' or ``example - Win32
- Debug.'' If you skip this step, V\Cpp{} will use the Debug
- configuration by default.
-
- \item
- Build the DLL. Choose \menuselection{Build \sub Build
- example_d.dll} in Debug mode, or \menuselection{Build \sub
- Build example.dll} in Release mode. This creates all
- intermediate and result files in a subdirectory called either
- \file{Debug} or \file{Release}, depending on which
- configuration you selected in the preceding step.
- \end{enumerate}
-
- \item
- \strong{Testing the debug-mode DLL}\\
- Once the Debug build has succeeded, bring up a DOS box, and change
- to the \file{example_nt\textbackslash Debug} directory. You
- should now be able to repeat the following session (\code{C>} is
- the DOS prompt, \code{>\code{>}>} is the Python prompt; note that
- build information and various debug output from Python may not
- match this screen dump exactly):
-
-\begin{verbatim}
-C>..\..\PCbuild\python_d
-Adding parser accelerators ...
-Done.
-Python 2.2 (#28, Dec 19 2001, 23:26:37) [MSC 32 bit (Intel)] on win32
-Type "copyright", "credits" or "license" for more information.
->>> import example
-[4897 refs]
->>> example.foo()
-Hello, world
-[4903 refs]
->>>
-\end{verbatim}
-
- Congratulations! You've successfully built your first Python
- extension module.
-
- \item
- \strong{Creating your own project}\\
- Choose a name and create a directory for it. Copy your C sources
- into it. Note that the module source file name does not
- necessarily have to match the module name, but the name of the
- initialization function should match the module name --- you can
- only import a module \module{spam} if its initialization function
- is called \cfunction{initspam()}, and it should call
- \cfunction{Py_InitModule()} with the string \code{"spam"} as its
- first argument (use the minimal \file{example.c} in this directory
- as a guide). By convention, it lives in a file called
- \file{spam.c} or \file{spammodule.c}. The output file should be
- called \file{spam.dll} or \file{spam.pyd} (the latter is supported
- to avoid confusion with a system library \file{spam.dll} to which
- your module could be a Python interface) in Release mode, or
- \file{spam_d.dll} or \file{spam_d.pyd} in Debug mode.
-
- Now your options are:
-
- \begin{enumerate}
- \item Copy \file{example.dsw} and \file{example.dsp}, rename
- them to \file{spam.*}, and edit them by hand, or
- \item Create a brand new project; instructions are below.
- \end{enumerate}
-
- In either case, copy \file{example_nt\textbackslash example.def}
- to \file{spam\textbackslash spam.def}, and edit the new
- \file{spam.def} so its second line contains the string
- `\code{initspam}'. If you created a new project yourself, add the
- file \file{spam.def} to the project now. (This is an annoying
- little file with only two lines. An alternative approach is to
- forget about the \file{.def} file, and add the option
- \programopt{/export:initspam} somewhere to the Link settings, by
- manually editing the setting in Project Options dialog).
-
- \item
- \strong{Creating a brand new project}\\
- Use the \menuselection{File \sub New \sub Projects} dialog to
- create a new Project Workspace. Select ``Win32 Dynamic-Link
- Library,'' enter the name (\samp{spam}), and make sure the
- Location is set to the \file{spam} directory you have created
- (which should be a direct subdirectory of the Python build tree, a
- sibling of \file{Include} and \file{PC}). Select Win32 as the
- platform (in my version, this is the only choice). Make sure the
- Create new workspace radio button is selected. Click OK.
-
- Now open the \menuselection{Project \sub Settings} dialog. You
- only need to change a few settings. Make sure All Configurations
- is selected from the Settings for: dropdown list. Select the
- C/\Cpp{} tab. Choose the Preprocessor category in the popup menu
- at the top. Type the following text in the entry box labeled
- Addditional include directories:
-
-\begin{verbatim}
-..\Include,..\PC
-\end{verbatim}
-
- Then, choose the Input category in the Link tab, and enter
-
-\begin{verbatim}
-..\PCbuild
-\end{verbatim}
-
- in the text box labelled ``Additional library path.''
-
- Now you need to add some mode-specific settings:
-
- Select ``Win32 Release'' in the ``Settings for'' dropdown list.
- Click the Link tab, choose the Input Category, and append
- \code{pythonXY.lib} to the list in the ``Object/library modules''
- box.
-
- Select ``Win32 Debug'' in the ``Settings for'' dropdown list, and
- append \code{pythonXY_d.lib} to the list in the ``Object/library
- modules'' box. Then click the C/\Cpp{} tab, select ``Code
- Generation'' from the Category dropdown list, and select ``Debug
- Multithreaded DLL'' from the ``Use run-time library'' dropdown
- list.
-
- Select ``Win32 Release'' again from the ``Settings for'' dropdown
- list. Select ``Multithreaded DLL'' from the ``Use run-time
- library:'' dropdown list.
-
- You should now create the file \file{spam.def} as instructed in the
- previous section. Then chose the \menuselection{Insert \sub Files
- into Project} dialog. Set the pattern to \code{*.*} and select
- both \file{spam.c} and \file{spam.def} and click OK. (Inserting
- them one by one is fine too.)
-\end{enumerate}
-
-
-If your module creates a new type, you may have trouble with this line:
-
-\begin{verbatim}
- PyObject_HEAD_INIT(&PyType_Type)
-\end{verbatim}
-
-Change it to:
-
-\begin{verbatim}
- PyObject_HEAD_INIT(NULL)
-\end{verbatim}
-
-and add the following to the module initialization function:
-
-\begin{verbatim}
- MyObject_Type.ob_type = &PyType_Type;
-\end{verbatim}
-
-Refer to section~3 of the
-\citetitle[http://www.python.org/doc/FAQ.html]{Python FAQ} for details
-on why you must do this.
-
-
-\section{Differences Between \UNIX{} and Windows
- \label{dynamic-linking}}
-\sectionauthor{Chris Phoenix}{cphoenix@best.com}
-
-
-\UNIX{} and Windows use completely different paradigms for run-time
-loading of code. Before you try to build a module that can be
-dynamically loaded, be aware of how your system works.
-
-In \UNIX, a shared object (\file{.so}) file contains code to be used by the
-program, and also the names of functions and data that it expects to
-find in the program. When the file is joined to the program, all
-references to those functions and data in the file's code are changed
-to point to the actual locations in the program where the functions
-and data are placed in memory. This is basically a link operation.
-
-In Windows, a dynamic-link library (\file{.dll}) file has no dangling
-references. Instead, an access to functions or data goes through a
-lookup table. So the DLL code does not have to be fixed up at runtime
-to refer to the program's memory; instead, the code already uses the
-DLL's lookup table, and the lookup table is modified at runtime to
-point to the functions and data.
-
-In \UNIX, there is only one type of library file (\file{.a}) which
-contains code from several object files (\file{.o}). During the link
-step to create a shared object file (\file{.so}), the linker may find
-that it doesn't know where an identifier is defined. The linker will
-look for it in the object files in the libraries; if it finds it, it
-will include all the code from that object file.
-
-In Windows, there are two types of library, a static library and an
-import library (both called \file{.lib}). A static library is like a
-\UNIX{} \file{.a} file; it contains code to be included as necessary.
-An import library is basically used only to reassure the linker that a
-certain identifier is legal, and will be present in the program when
-the DLL is loaded. So the linker uses the information from the
-import library to build the lookup table for using identifiers that
-are not included in the DLL. When an application or a DLL is linked,
-an import library may be generated, which will need to be used for all
-future DLLs that depend on the symbols in the application or DLL.
-
-Suppose you are building two dynamic-load modules, B and C, which should
-share another block of code A. On \UNIX, you would \emph{not} pass
-\file{A.a} to the linker for \file{B.so} and \file{C.so}; that would
-cause it to be included twice, so that B and C would each have their
-own copy. In Windows, building \file{A.dll} will also build
-\file{A.lib}. You \emph{do} pass \file{A.lib} to the linker for B and
-C. \file{A.lib} does not contain code; it just contains information
-which will be used at runtime to access A's code.
-
-In Windows, using an import library is sort of like using \samp{import
-spam}; it gives you access to spam's names, but does not create a
-separate copy. On \UNIX, linking with a library is more like
-\samp{from spam import *}; it does create a separate copy.
-
-
-\section{Using DLLs in Practice \label{win-dlls}}
-\sectionauthor{Chris Phoenix}{cphoenix@best.com}
-
-Windows Python is built in Microsoft Visual \Cpp; using other
-compilers may or may not work (though Borland seems to). The rest of
-this section is MSV\Cpp{} specific.
-
-When creating DLLs in Windows, you must pass \file{pythonXY.lib} to
-the linker. To build two DLLs, spam and ni (which uses C functions
-found in spam), you could use these commands:
-
-\begin{verbatim}
-cl /LD /I/python/include spam.c ../libs/pythonXY.lib
-cl /LD /I/python/include ni.c spam.lib ../libs/pythonXY.lib
-\end{verbatim}
-
-The first command created three files: \file{spam.obj},
-\file{spam.dll} and \file{spam.lib}. \file{Spam.dll} does not contain
-any Python functions (such as \cfunction{PyArg_ParseTuple()}), but it
-does know how to find the Python code thanks to \file{pythonXY.lib}.
-
-The second command created \file{ni.dll} (and \file{.obj} and
-\file{.lib}), which knows how to find the necessary functions from
-spam, and also from the Python executable.
-
-Not every identifier is exported to the lookup table. If you want any
-other modules (including Python) to be able to see your identifiers,
-you have to say \samp{_declspec(dllexport)}, as in \samp{void
-_declspec(dllexport) initspam(void)} or \samp{PyObject
-_declspec(dllexport) *NiGetSpamData(void)}.
-
-Developer Studio will throw in a lot of import libraries that you do
-not really need, adding about 100K to your executable. To get rid of
-them, use the Project Settings dialog, Link tab, to specify
-\emph{ignore default libraries}. Add the correct
-\file{msvcrt\var{xx}.lib} to the list of libraries.
diff --git a/Doc/html/.cvsignore b/Doc/html/.cvsignore
deleted file mode 100644
index 1c64adcbd3..0000000000
--- a/Doc/html/.cvsignore
+++ /dev/null
@@ -1,14 +0,0 @@
-api
-doc
-ext
-lib
-mac
-ref
-tut
-dist
-inst
-whatsnew
-acks.html
-index.html
-modindex.html
-@webchecker.pickle
diff --git a/Doc/html/about.dat b/Doc/html/about.dat
deleted file mode 100644
index e6f8b55ce3..0000000000
--- a/Doc/html/about.dat
+++ /dev/null
@@ -1,24 +0,0 @@
-
This document was generated using the
- LaTeX2HTML translator.
-
The application of
- LaTeX2HTML to the Python
- documentation has been heavily tailored by Fred L. Drake,
- Jr. Original navigation icons were contributed by Christopher
- Petrilli.
-
The Python documentation was originally written by Guido van
- Rossum, but has increasingly become a community effort over the
- past several years. This growing collection of documents is
- available in several formats, including typeset versions in PDF
- and PostScript for printing, from the Python Web site.
-
-
General comments and questions regarding this document should
- be sent by email to python-docs@python.org. If you find specific errors in
- this document, please report the bug at the Python Bug
- Tracker at SourceForge.
-
-
-
Questions regarding how to use the information in this
- document should be sent to the Python news group, comp.lang.python, or the Python mailing list (which is gated to the newsgroup and
- carries the same content).
-
-
-
For any of these channels, please be sure not to send HTML email.
- Thanks.
-
-
- See About the Python Documentation
- for information on suggesting changes.
-
-
-
diff --git a/Doc/html/stdabout.dat b/Doc/html/stdabout.dat
deleted file mode 100644
index bf0f1e6ff5..0000000000
--- a/Doc/html/stdabout.dat
+++ /dev/null
@@ -1,49 +0,0 @@
-
This document was generated using the
- LaTeX2HTML translator.
-
The application of
- LaTeX2HTML to the Python
- documentation has been heavily tailored by Fred L. Drake,
- Jr. Original navigation icons were contributed by Christopher
- Petrilli.
-
-
-
-
-
Comments and Questions
-
-
General comments and questions regarding this document should
- be sent by email to python-docs@python.org. If you find specific errors in
- this document, either in the content or the presentation, please
- report the bug at the Python Bug
- Tracker at SourceForge.
-
-
-
Questions regarding how to use the information in this
- document should be sent to the Python news group, comp.lang.python, or the Python mailing list (which is gated to the newsgroup and
- carries the same content).
-
-
-
For any of these channels, please be sure not to send HTML email.
- Thanks.
-
diff --git a/Doc/html/style.css b/Doc/html/style.css
deleted file mode 100644
index 4a9549fd41..0000000000
--- a/Doc/html/style.css
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * The first part of this is the standard CSS generated by LaTeX2HTML,
- * with the "empty" declarations removed.
- */
-
-/* Century Schoolbook font is very similar to Computer Modern Math: cmmi */
-.math { font-family: "Century Schoolbook", serif; }
-.math i { font-family: "Century Schoolbook", serif;
- font-weight: bold }
-.boldmath { font-family: "Century Schoolbook", serif;
- font-weight: bold }
-
-/*
- * Implement both fixed-size and relative sizes.
- *
- * I think these can be safely removed, as it doesn't appear that
- * LaTeX2HTML ever generates these, even though these are carried
- * over from the LaTeX2HTML stylesheet.
- */
-small.xtiny { font-size : xx-small; }
-small.tiny { font-size : x-small; }
-small.scriptsize { font-size : smaller; }
-small.footnotesize { font-size : small; }
-big.xlarge { font-size : large; }
-big.xxlarge { font-size : x-large; }
-big.huge { font-size : larger; }
-big.xhuge { font-size : xx-large; }
-
-/*
- * Document-specific styles come next;
- * these are added for the Python documentation.
- *
- * Note that the size specifications for the H* elements are because
- * Netscape on Solaris otherwise doesn't get it right; they all end up
- * the normal text size.
- */
-
-body { color: #000000;
- background-color: #ffffff; }
-
-a:active { color: #ff0000; }
-a[href]:hover { background-color: #bbeeff; }
-a:visited { color: #551a8b; }
-a:link { color: #0000bb; }
-
-h1, h2, h3, h4, h5, h6 { font-family: avantgarde, sans-serif;
- font-weight: bold; }
-h1 { font-size: 180%; }
-h2 { font-size: 150%; }
-h3, h4 { font-size: 120%; }
-code, tt { font-family: lucida typewriter, lucidatypewriter,
- monospace; }
-var { font-family: times, serif;
- font-style: italic;
- font-weight: normal; }
-
-.typelabel { font-family: lucida, sans-serif; }
-
-.navigation td { background-color: #99ccff;
- font-weight: bold;
- font-family: avantgarde, sans-serif;
- font-size: 110%; }
-
-div.warning { background-color: #fffaf0;
- border: thin solid black;
- padding: 0.5em;
- margin-left: 2em;
- margin-right: 2em; }
-
-div.warning .label { font-family: sans-serif;
- font-size: 110%;
- margin-right: 0.5em; }
-
-div.note { background-color: #fffaf0;
- border: thin solid black;
- padding: 0.5em;
- margin-left: 2em;
- margin-right: 2em; }
-
-div.note .label { margin-right: 0.5em;
- font-family: sans-serif; }
-
-.release-info { font-style: italic; }
-
-.titlegraphic { vertical-align: top; }
-
-.verbatim pre { color: #00008b;
- font-family: lucida typewriter, lucidatypewriter,
- monospace;
- font-size: 90%; }
-.verbatim { margin-left: 2em; }
-.verbatim .footer { padding: 0.05in;
- font-size: 85%;
- background-color: #99ccff;
- margin-right: 0.5in; }
-
-.grammar { background-color: #99ccff;
- margin-right: 0.5in;
- padding: 0.05in; }
-.productions { background-color: #bbeeff; }
-.productions a:hover { background-color: #99ccff; }
-.productions table { vertical-align: baseline; }
-.grammar-footer { padding: 0.05in;
- font-size: 85%; }
-
-.email { font-family: avantgarde, sans-serif; }
-.mailheader { font-family: avantgarde, sans-serif; }
-.mimetype { font-family: avantgarde, sans-serif; }
-.newsgroup { font-family: avantgarde, sans-serif; }
-.url { font-family: avantgarde, sans-serif; }
-.file { font-family: avantgarde, sans-serif; }
-
-.tableheader { background-color: #99ccff;
- font-family: avantgarde, sans-serif; }
-
-.refcount-info { font-style: italic; }
-.refcount-info .value { font-weight: bold;
- color: #006600; }
-
-/*
- * Some decoration for the "See also:" blocks, in part inspired by some of
- * the styling on Lars Marius Garshol's XSA pages.
- * (The blue in the navigation bars is #99CCFF.)
- */
-.seealso { background-color: #fffaf0;
- border: thin solid black;
- padding: 4pt; }
-
-.seealso .heading { font-size: 110%; }
-
-/*
- * Class 'availability' is used for module availability statements at
- * the top of modules.
- */
-.availability .platform { font-weight: bold; }
diff --git a/Doc/info/.cvsignore b/Doc/info/.cvsignore
deleted file mode 100644
index e8db0b5b88..0000000000
--- a/Doc/info/.cvsignore
+++ /dev/null
@@ -1,2 +0,0 @@
-*.info*
-*.texi
diff --git a/Doc/info/Makefile b/Doc/info/Makefile
deleted file mode 100644
index 008e3692b5..0000000000
--- a/Doc/info/Makefile
+++ /dev/null
@@ -1,70 +0,0 @@
-# Generate the Python "info" documentation.
-
-TOPDIR=..
-TOOLSDIR=$(TOPDIR)/tools
-HTMLDIR=$(TOPDIR)/html
-
-# The emacs binary used to build the info docs. GNU Emacs 21 is required.
-EMACS=emacs
-
-MKINFO=$(TOOLSDIR)/mkinfo
-SCRIPTS=$(TOOLSDIR)/checkargs.pm $(TOOLSDIR)/mkinfo $(TOOLSDIR)/py2texi.el
-
-# set VERSION to code the VERSION number into the info file name
-# allowing installation of more than one set of python info docs
-# into the same directory
-VERSION=
-
-all: check-emacs-version \
- python$(VERSION)-api.info python$(VERSION)-ext.info \
- python$(VERSION)-lib.info python$(VERSION)-ref.info \
- python$(VERSION)-tut.info python$(VERSION)-dist.info
-
-# python$(VERSION)-doc.info python$(VERSION)-inst.info
-# python$(VERSION)-mac.info
-
-check-emacs-version:
- @v="`$(EMACS) --version 2>&1 | egrep '^(GNU |X)Emacs [12]*'`"; \
- if `echo "$$v" | grep '^GNU Emacs 21' >/dev/null 2>&1`; then \
- echo "Using $(EMACS) to build the info docs"; \
- else \
- echo "GNU Emacs 21 is required to build the info docs"; \
- echo "Found $$v"; \
- false; \
- fi
-
-python$(VERSION)-api.info: ../api/api.tex $(SCRIPTS)
- EMACS=$(EMACS) $(MKINFO) $< $*.texi $@
-
-python$(VERSION)-ext.info: ../ext/ext.tex $(SCRIPTS)
- EMACS=$(EMACS) $(MKINFO) $< $*.texi $@
-
-python$(VERSION)-lib.info: ../lib/lib.tex $(SCRIPTS)
- EMACS=$(EMACS) $(MKINFO) $< $*.texi $@
-
-# Not built by default; the conversion doesn't really handle it well.
-python$(VERSION)-mac.info: ../mac/mac.tex $(SCRIPTS)
- EMACS=$(EMACS) $(MKINFO) $< $*.texi $@
-
-python$(VERSION)-ref.info: ../ref/ref.tex $(SCRIPTS)
- EMACS=$(EMACS) $(MKINFO) $< $*.texi $@
-
-python$(VERSION)-tut.info: ../tut/tut.tex $(SCRIPTS)
- EMACS=$(EMACS) $(MKINFO) $< $*.texi $@
-
-# Not built by default; the conversion doesn't handle it at all.
-python$(VERSION)-doc.info: ../doc/doc.tex $(SCRIPTS)
- EMACS=$(EMACS) $(MKINFO) $< $*.texi $@
-
-python$(VERSION)-dist.info: ../dist/dist.tex $(SCRIPTS)
- EMACS=$(EMACS) $(MKINFO) $< $*.texi $@
-
-# Not built by default; the conversion chokes on two @end multitable's
-python$(VERSION)-inst.info: ../inst/inst.tex $(SCRIPTS)
- EMACS=$(EMACS) $(MKINFO) $< $*.texi $@
-
-clean:
- rm -f *.texi~ *.texi
-
-clobber: clean
- rm -f *.texi python*-*.info python*-*.info-[0-9]*
diff --git a/Doc/info/README b/Doc/info/README
deleted file mode 100644
index 802314412c..0000000000
--- a/Doc/info/README
+++ /dev/null
@@ -1,21 +0,0 @@
-This archive contains the standard Python documentation in GNU info
-format. Five manuals are included:
-
- python-ref.info* Python Reference Manual
- python-mac.info* Python Macintosh Modules
- python-lib.info* Python Library Reference
- python-ext.info* Extending and Embedding the Python Interpreter
- python-api.info* Python/C API Reference
- python-tut.info* Python Tutorial
-
-The file python.dir is a fragment of a "dir" file that can be used to
-incorporate these documents into an existing GNU info installation:
-insert the contents of this file into the "dir" or "localdir" file at
-an appropriate point and copy the python-*.info* files to the same
-directory.
-
-Thanks go to Milan Zamazal for providing this
-conversion to the info format.
-
-Questions and comments on these documents should be directed to
-python-docs@python.org.
diff --git a/Doc/info/python.dir b/Doc/info/python.dir
deleted file mode 100644
index dce2bb322a..0000000000
--- a/Doc/info/python.dir
+++ /dev/null
@@ -1,12 +0,0 @@
-
-Python Standard Documentation
-
-* Python Library: (python-lib). Python Library Reference
-* Python Mac Modules: (python-mac). Python Macintosh Modules
-* Python Reference: (python-ref). Python Reference Manual
-* Python API: (python-api). Python/C API Reference Manual
-* Python Extending: (python-ext). Extending & Embedding Python
-* Python Tutorial: (python-tut). Python Tutorial
-* Documenting Python: (python-doc). Documenting Python
-* Installing Modules: (python-inst). Installing Python Modules
-* Distributing Modules: (python-dist). Distributing Python Modules
diff --git a/Doc/inst/inst.tex b/Doc/inst/inst.tex
deleted file mode 100644
index bfc996e872..0000000000
--- a/Doc/inst/inst.tex
+++ /dev/null
@@ -1,1136 +0,0 @@
-\documentclass{howto}
-\usepackage{distutils}
-
-% TODO:
-% Fill in XXX comments
-
-\title{Installing Python Modules}
-
-% The audience for this document includes people who don't know anything
-% about Python and aren't about to learn the language just in order to
-% install and maintain it for their users, i.e. system administrators.
-% Thus, I have to be sure to explain the basics at some point:
-% sys.path and PYTHONPATH at least. Should probably give pointers to
-% other docs on "import site", PYTHONSTARTUP, PYTHONHOME, etc.
-%
-% Finally, it might be useful to include all the material from my "Care
-% and Feeding of a Python Installation" talk in here somewhere. Yow!
-
-\author{Greg Ward}
-\authoraddress{Email: \email{distutils-sig@python.org}}
-
-\makeindex
-
-\begin{document}
-
-\maketitle
-
-\begin{abstract}
- \noindent
- This document describes the Python Distribution Utilities
- (``Distutils'') from the end-user's point-of-view, describing how to
- extend the capabilities of a standard Python installation by building
- and installing third-party Python modules and extensions.
-\end{abstract}
-
-%\begin{abstract}
-%\noindent
-%Abstract this!
-%\end{abstract}
-
-
-% The ugly "%begin{latexonly}" pseudo-environment supresses the table
-% of contents for HTML generation.
-%
-%begin{latexonly}
-\tableofcontents
-%end{latexonly}
-
-
-\section{Introduction}
-\label{intro}
-
-Although Python's extensive standard library covers many programming
-needs, there often comes a time when you need to add some new
-functionality to your Python installation in the form of third-party
-modules. This might be necessary to support your own programming, or to
-support an application that you want to use and that happens to be
-written in Python.
-
-In the past, there has been little support for adding third-party
-modules to an existing Python installation. With the introduction of
-the Python Distribution Utilities (Distutils for short) in Python 2.0,
-this changed.
-
-This document is aimed primarily at the people who need to install
-third-party Python modules: end-users and system administrators who just
-need to get some Python application running, and existing Python
-programmers who want to add some new goodies to their toolbox. You
-don't need to know Python to read this document; there will be some
-brief forays into using Python's interactive mode to explore your
-installation, but that's it. If you're looking for information on how
-to distribute your own Python modules so that others may use them, see
-the \citetitle[../dist/dist.html]{Distributing Python Modules} manual.
-
-
-\subsection{Best case: trivial installation}
-\label{trivial-install}
-
-In the best case, someone will have prepared a special version of the
-module distribution you want to install that is targeted specifically at
-your platform and is installed just like any other software on your
-platform. For example, the module developer might make an executable
-installer available for Windows users, an RPM package for users of
-RPM-based Linux systems (Red Hat, SuSE, Mandrake, and many others), a
-Debian package for users of Debian-based Linux systems, and so forth.
-
-In that case, you would download the installer appropriate to your
-platform and do the obvious thing with it: run it if it's an executable
-installer, \code{rpm --install} it if it's an RPM, etc. You don't need
-to run Python or a setup script, you don't need to compile
-anything---you might not even need to read any instructions (although
-it's always a good idea to do so anyways).
-
-Of course, things will not always be that easy. You might be interested
-in a module distribution that doesn't have an easy-to-use installer for
-your platform. In that case, you'll have to start with the source
-distribution released by the module's author/maintainer. Installing
-from a source distribution is not too hard, as long as the modules are
-packaged in the standard way. The bulk of this document is about
-building and installing modules from standard source distributions.
-
-
-\subsection{The new standard: Distutils}
-\label{new-standard}
-
-If you download a module source distribution, you can tell pretty
-quickly if it was packaged and distributed in the standard way, i.e.
-using the Distutils. First, the distribution's name and version number
-will be featured prominently in the name of the downloaded archive, e.g.
-\file{foo-1.0.tar.gz} or \file{widget-0.9.7.zip}. Next, the archive
-will unpack into a similarly-named directory: \file{foo-1.0} or
-\file{widget-0.9.7}. Additionally, the distribution will contain a
-setup script \file{setup.py}, and a file named \file{README.txt} or possibly
-just \file{README}, which should explain that building and installing the
-module distribution is a simple matter of running
-
-\begin{verbatim}
-python setup.py install
-\end{verbatim}
-
-If all these things are true, then you already know how to build and
-install the modules you've just downloaded: Run the command above.
-Unless you need to install things in a non-standard way or customize the
-build process, you don't really need this manual. Or rather, the above
-command is everything you need to get out of this manual.
-
-
-\section{Standard Build and Install}
-\label{standard-install}
-
-As described in section~\ref{new-standard}, building and installing
-a module distribution using the Distutils is usually one simple command:
-
-\begin{verbatim}
-python setup.py install
-\end{verbatim}
-
-On \UNIX, you'd run this command from a shell prompt; on Windows, you
-have to open a command prompt window (``DOS box'') and do it there; on
-Mac OS, things are a tad more complicated (see below).
-
-
-\subsection{Platform variations}
-\label{platform-variations}
-
-You should always run the setup command from the distribution root
-directory, i.e. the top-level subdirectory that the module source
-distribution unpacks into. For example, if you've just downloaded a
-module source distribution \file{foo-1.0.tar.gz} onto a
-\UNIX{} system, the normal thing to do is:
-
-\begin{verbatim}
-gunzip -c foo-1.0.tar.gz | tar xf - # unpacks into directory foo-1.0
-cd foo-1.0
-python setup.py install
-\end{verbatim}
-
-On Windows, you'd probably download \file{foo-1.0.zip}. If you
-downloaded the archive file to \file{C:\textbackslash{}Temp}, then it
-would unpack into \file{C:\textbackslash{}Temp\textbackslash{}foo-1.0};
-you can use either a archive manipulator with a grapical user interface
-(such as WinZip) or a command-line tool (such as \program{unzip} or
-\program{pkunzip}) to unpack the archive. Then, open a command prompt
-window (``DOS box''), and run:
-
-\begin{verbatim}
-cd c:\Temp\foo-1.0
-python setup.py install
-\end{verbatim}
-
-On Mac OS 9, you double-click the \file{setup.py} script. It will bring
-up a dialog where you can select the \command{install} command. Then
-selecting the \command{run} button will install your distribution.
-The dialog is built dynamically, so all commands and options for this
-specific distribution are listed.
-
-\subsection{Splitting the job up}
-\label{splitting-up}
-
-Running \code{setup.py install} builds and installs all modules in one
-run. If you prefer to work incrementally---especially useful if you
-want to customize the build process, or if things are going wrong---you
-can use the setup script to do one thing at a time. This is
-particularly helpful when the build and install will be done by
-different users---for example, you might want to build a module distribution
-and hand it off to a system administrator for installation (or do it
-yourself, with super-user privileges).
-
-For example, you can build everything in one step, and then install
-everything in a second step, by invoking the setup script twice:
-
-\begin{verbatim}
-python setup.py build
-python setup.py install
-\end{verbatim}
-
-If you do this, you will notice that running the \command{install}
-command first runs the \command{build} command, which---in this
-case---quickly notices that it has nothing to do, since everything in
-the \file{build} directory is up-to-date.
-
-You may not need this ability to break things down often if all you do
-is install modules downloaded off the 'net, but it's very handy for more
-advanced tasks. If you get into distributing your own Python modules
-and extensions, you'll run lots of individual Distutils commands on
-their own.
-
-
-\subsection{How building works}
-\label{how-build-works}
-
-As implied above, the \command{build} command is responsible for putting
-the files to install into a \emph{build directory}. By default, this is
-\file{build} under the distribution root; if you're excessively
-concerned with speed, or want to keep the source tree pristine, you can
-change the build directory with the \longprogramopt{build-base} option.
-For example:
-
-\begin{verbatim}
-python setup.py build --build-base=/tmp/pybuild/foo-1.0
-\end{verbatim}
-
-(Or you could do this permanently with a directive in your system or
-personal Distutils configuration file; see
-section~\ref{config-files}.) Normally, this isn't necessary.
-
-The default layout for the build tree is as follows:
-
-\begin{verbatim}
---- build/ --- lib/
-or
---- build/ --- lib./
- temp./
-\end{verbatim}
-
-where \code{} expands to a brief description of the current
-OS/hardware platform and Python version. The first form, with just a
-\file{lib} directory, is used for ``pure module distributions''---that
-is, module distributions that include only pure Python modules. If a
-module distribution contains any extensions (modules written in C/\Cpp),
-then the second form, with two \code{} directories, is used. In
-that case, the \file{temp.\filevar{plat}} directory holds temporary
-files generated by the compile/link process that don't actually get
-installed. In either case, the \file{lib} (or
-\file{lib.\filevar{plat}}) directory contains all Python modules (pure
-Python and extensions) that will be installed.
-
-In the future, more directories will be added to handle Python scripts,
-documentation, binary executables, and whatever else is needed to handle
-the job of installing Python modules and applications.
-
-
-\subsection{How installation works}
-\label{how-install-works}
-
-After the \command{build} command runs (whether you run it explicitly,
-or the \command{install} command does it for you), the work of the
-\command{install} command is relatively simple: all it has to do is copy
-everything under \file{build/lib} (or \file{build/lib.\filevar{plat}})
-to your chosen installation directory.
-
-If you don't choose an installation directory---i.e., if you just run
-\code{setup.py install}---then the \command{install} command installs to
-the standard location for third-party Python modules. This location
-varies by platform and by how you built/installed Python itself. On
-\UNIX{} and Mac OS, it also depends on whether the module distribution
-being installed is pure Python or contains extensions (``non-pure''):
-\begin{tableiv}{l|l|l|c}{textrm}%
- {Platform}{Standard installation location}{Default value}{Notes}
- \lineiv{\UNIX{} (pure)}
- {\filenq{\filevar{prefix}/lib/python2.0/site-packages}}
- {\filenq{/usr/local/lib/python2.0/site-packages}}
- {(1)}
- \lineiv{\UNIX{} (non-pure)}
- {\filenq{\filevar{exec-prefix}/lib/python2.0/site-packages}}
- {\filenq{/usr/local/lib/python2.0/site-packages}}
- {(1)}
- \lineiv{Windows}
- {\filenq{\filevar{prefix}}}
- {\filenq{C:\textbackslash{}Python}}
- {(2)}
- \lineiv{Mac OS (pure)}
- {\filenq{\filevar{prefix}:Lib:site-packages}}
- {\filenq{Python:Lib:site-packages}}
- {}
- \lineiv{Mac OS (non-pure)}
- {\filenq{\filevar{prefix}:Lib:site-packages}}
- {\filenq{Python:Lib:site-packages}}
- {}
-\end{tableiv}
-
-\noindent Notes:
-\begin{description}
-\item[(1)] Most Linux distributions include Python as a standard part of
- the system, so \filevar{prefix} and \filevar{exec-prefix} are usually
- both \file{/usr} on Linux. If you build Python yourself on Linux (or
- any \UNIX-like system), the default \filevar{prefix} and
- \filevar{exec-prefix} are \file{/usr/local}.
-\item[(2)] The default installation directory on Windows was
- \file{C:\textbackslash{}Program Files\textbackslash{}Python} under
- Python 1.6a1, 1.5.2, and earlier.
-\end{description}
-
-\filevar{prefix} and \filevar{exec-prefix} stand for the directories
-that Python is installed to, and where it finds its libraries at
-run-time. They are always the same under Windows and Mac OS, and very
-often the same under \UNIX. You can find out what your Python
-installation uses for \filevar{prefix} and \filevar{exec-prefix} by
-running Python in interactive mode and typing a few simple commands.
-Under \UNIX, just type \code{python} at the shell prompt. Under
-Windows, choose \menuselection{Start \sub Programs \sub Python
-2.1 \sub Python (command line)}. Under Mac OS 9, start \file{PythonInterpreter}.
-Once the interpreter is started, you type Python code at the
-prompt. For example, on my Linux system, I type the three Python
-statements shown below, and get the output as shown, to find out my
-\filevar{prefix} and \filevar{exec-prefix}:
-
-\begin{verbatim}
-Python 1.5.2 (#1, Apr 18 1999, 16:03:16) [GCC pgcc-2.91.60 19981201 (egcs-1.1.1 on linux2
-Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
->>> import sys
->>> sys.prefix
-'/usr'
->>> sys.exec_prefix
-'/usr'
-\end{verbatim}
-
-If you don't want to install modules to the standard location, or if you
-don't have permission to write there, then you need to read about
-alternate installations in section~\ref{alt-install}. If you want to
-customize your installation directories more heavily, see
-section~\ref{custom-install} on custom installations.
-
-
-% This rather nasty macro is used to generate the tables that describe
-% each installation scheme. It's nasty because it takes two arguments
-% for each "slot" in an installation scheme, there will soon be more
-% than five of these slots, and TeX has a limit of 10 arguments to a
-% macro. Uh-oh.
-
-\newcommand{\installscheme}[8]
- {\begin{tableiii}{lll}{textrm}
- {Type of file}
- {Installation Directory}
- {Override option}
- \lineiii{pure module distribution}
- {\filevar{#1}\filenq{#2}}
- {\longprogramopt{install-purelib}}
- \lineiii{non-pure module distribution}
- {\filevar{#3}\filenq{#4}}
- {\longprogramopt{install-platlib}}
- \lineiii{scripts}
- {\filevar{#5}\filenq{#6}}
- {\longprogramopt{install-scripts}}
- \lineiii{data}
- {\filevar{#7}\filenq{#8}}
- {\longprogramopt{install-data}}
- \end{tableiii}}
-
-
-\section{Alternate Installation}
-\label{alt-install}
-
-Often, it is necessary or desirable to install modules to a location
-other than the standard location for third-party Python modules. For
-example, on a \UNIX{} system you might not have permission to write to the
-standard third-party module directory. Or you might wish to try out a
-module before making it a standard part of your local Python
-installation. This is especially true when upgrading a distribution
-already present: you want to make sure your existing base of scripts
-still works with the new version before actually upgrading.
-
-The Distutils \command{install} command is designed to make installing
-module distributions to an alternate location simple and painless. The
-basic idea is that you supply a base directory for the installation, and
-the \command{install} command picks a set of directories (called an
-\emph{installation scheme}) under this base directory in which to
-install files. The details differ across platforms, so read whichever
-of the following sections applies to you.
-
-
-\subsection{Alternate installation: \UNIX{} (the home scheme)}
-\label{alt-install-prefix}
-
-Under \UNIX, there are two ways to perform an alternate installation.
-The ``prefix scheme'' is similar to how alternate installation works
-under Windows and Mac OS, but is not necessarily the most useful way to
-maintain a personal Python library. Hence, we document the more
-convenient and commonly useful ``home scheme'' first.
-
-The idea behind the ``home scheme'' is that you build and maintain a
-personal stash of Python modules, probably under your home directory.
-Installing a new module distribution is as simple as
-
-\begin{verbatim}
-python setup.py install --home=
-\end{verbatim}
-
-where you can supply any directory you like for the \longprogramopt{home}
-option. Lazy typists can just type a tilde (\code{\textasciitilde}); the
-\command{install} command will expand this to your home directory:
-
-\begin{verbatim}
-python setup.py install --home=~
-\end{verbatim}
-
-The \longprogramopt{home} option defines the installation base
-directory. Files are installed to the following directories under the
-installation base as follows:
-\installscheme{home}{/lib/python}
- {home}{/lib/python}
- {home}{/bin}
- {home}{/share}
-
-\subsection{Alternate installation: \UNIX{} (the prefix scheme)}
-\label{alt-install-home}
-
-The ``prefix scheme'' is useful when you wish to use one Python
-installation to perform the build/install (i.e., to run the setup
-script), but install modules into the third-party module directory of a
-different Python installation (or something that looks like a different
-Python installation). If this sounds a trifle unusual, it is---that's
-why the ``home scheme'' comes first. However, there are at least two
-known cases where the prefix scheme will be useful.
-
-First, consider that many Linux distributions put Python in \file{/usr},
-rather than the more traditional \file{/usr/local}. This is entirely
-appropriate, since in those cases Python is part of ``the system''
-rather than a local add-on. However, if you are installing Python
-modules from source, you probably want them to go in
-\file{/usr/local/lib/python2.\filevar{X}} rather than
-\file{/usr/lib/python2.\filevar{X}}. This can be done with
-
-\begin{verbatim}
-/usr/bin/python setup.py install --prefix=/usr/local
-\end{verbatim}
-
-Another possibility is a network filesystem where the name used to write
-to a remote directory is different from the name used to read it: for
-example, the Python interpreter accessed as \file{/usr/local/bin/python}
-might search for modules in \file{/usr/local/lib/python2.\filevar{X}},
-but those modules would have to be installed to, say,
-\file{/mnt/\filevar{@server}/export/lib/python2.\filevar{X}}. This
-could be done with
-
-\begin{verbatim}
-/usr/local/bin/python setup.py install --prefix=/mnt/@server/export
-\end{verbatim}
-
-In either case, the \longprogramopt{prefix} option defines the
-installation base, and the \longprogramopt{exec-prefix} option defines
-the platform-specific installation base, which is used for
-platform-specific files. (Currently, this just means non-pure module
-distributions, but could be expanded to C libraries, binary executables,
-etc.) If \longprogramopt{exec-prefix} is not supplied, it defaults to
-\longprogramopt{prefix}. Files are installed as follows:
-
-\installscheme{prefix}{/lib/python2.\filevar{X}/site-packages}
- {exec-prefix}{/lib/python2.\filevar{X}/site-packages}
- {prefix}{/bin}
- {prefix}{/share}
-
-There is no requirement that \longprogramopt{prefix} or
-\longprogramopt{exec-prefix} actually point to an alternate Python
-installation; if the directories listed above do not already exist, they
-are created at installation time.
-
-Incidentally, the real reason the prefix scheme is important is simply
-that a standard \UNIX{} installation uses the prefix scheme, but with
-\longprogramopt{prefix} and \longprogramopt{exec-prefix} supplied by
-Python itself as \code{sys.prefix} and \code{sys.exec\_prefix}. Thus,
-you might think you'll never use the prefix scheme, but every time you
-run \code{python setup.py install} without any other options, you're
-using it.
-
-Note that installing extensions to an alternate Python installation has
-no effect on how those extensions are built: in particular, the Python
-header files (\file{Python.h} and friends) installed with the Python
-interpreter used to run the setup script will be used in compiling
-extensions. It is your responsibility to ensure that the interpreter
-used to run extensions installed in this way is compatible with the
-interpreter used to build them. The best way to do this is to ensure
-that the two interpreters are the same version of Python (possibly
-different builds, or possibly copies of the same build). (Of course, if
-your \longprogramopt{prefix} and \longprogramopt{exec-prefix} don't even
-point to an alternate Python installation, this is immaterial.)
-
-
-\subsection{Alternate installation: Windows}
-\label{alt-install-windows}
-
-Since Windows has no conception of a user's home directory, and since
-the standard Python installation under Windows is simpler than that
-under \UNIX, there's no point in having separate \longprogramopt{prefix}
-and \longprogramopt{home} options. Just use the \longprogramopt{prefix}
-option to specify a base directory, e.g.
-
-\begin{verbatim}
-python setup.py install --prefix="\Temp\Python"
-\end{verbatim}
-
-to install modules to the
-\file{\textbackslash{}Temp\textbackslash{}Python} directory on the
-current drive.
-
-The installation base is defined by the \longprogramopt{prefix} option;
-the \longprogramopt{exec-prefix} option is not supported under Windows.
-Files are installed as follows:
-\installscheme{prefix}{}
- {prefix}{}
- {prefix}{\textbackslash{}Scripts}
- {prefix}{\textbackslash{}Data}
-
-
-\subsection{Alternate installation: Mac OS 9}
-\label{alt-install-macos}
-
-% XXX Mac OS X?
-
-Like Windows, Mac OS has no notion of home directories (or even of
-users), and a fairly simple standard Python installation. Thus, only a
-\longprogramopt{prefix} option is needed. It defines the installation
-base, and files are installed under it as follows:
-
-\installscheme{prefix}{:Lib:site-packages}
- {prefix}{:Lib:site-packages}
- {prefix}{:Scripts}
- {prefix}{:Data}
-
-See section~\ref{platform-variations} for information on supplying
-command-line arguments to the setup script with MacPython.
-
-
-\section{Custom Installation}
-\label{custom-install}
-
-Sometimes, the alternate installation schemes described in
-section~\ref{alt-install} just don't do what you want. You might
-want to tweak just one or two directories while keeping everything under
-the same base directory, or you might want to completely redefine the
-installation scheme. In either case, you're creating a \emph{custom
-installation scheme}.
-
-You probably noticed the column of ``override options'' in the tables
-describing the alternate installation schemes above. Those options are
-how you define a custom installation scheme. These override options can
-be relative, absolute, or explicitly defined in terms of one of the
-installation base directories. (There are two installation base
-directories, and they are normally the same---they only differ when you
-use the \UNIX{} ``prefix scheme'' and supply different
-\longprogramopt{prefix} and \longprogramopt{exec-prefix} options.)
-
-For example, say you're installing a module distribution to your home
-directory under \UNIX---but you want scripts to go in
-\file{\textasciitilde/scripts} rather than \file{\textasciitilde/bin}.
-As you might expect, you can override this directory with the
-\longprogramopt{install-scripts} option; in this case, it makes most
-sense to supply a relative path, which will be interpreted relative to
-the installation base directory (your home directory, in this case):
-
-\begin{verbatim}
-python setup.py install --home=~ --install-scripts=scripts
-\end{verbatim}
-
-Another \UNIX{} example: suppose your Python installation was built and
-installed with a prefix of \file{/usr/local/python}, so under a standard
-installation scripts will wind up in \file{/usr/local/python/bin}. If
-you want them in \file{/usr/local/bin} instead, you would supply this
-absolute directory for the \longprogramopt{install-scripts} option:
-
-\begin{verbatim}
-python setup.py install --install-scripts=/usr/local/bin
-\end{verbatim}
-
-(This performs an installation using the ``prefix scheme,'' where the
-prefix is whatever your Python interpreter was installed with---
-\file{/usr/local/python} in this case.)
-
-If you maintain Python on Windows, you might want third-party modules to
-live in a subdirectory of \filevar{prefix}, rather than right in
-\filevar{prefix} itself. This is almost as easy as customizing the
-script installation directory---you just have to remember that there are
-two types of modules to worry about, pure modules and non-pure modules
-(i.e., modules from a non-pure distribution). For example:
-
-\begin{verbatim}
-python setup.py install --install-purelib=Site --install-platlib=Site
-\end{verbatim}
-
-The specified installation directories are relative to
-\filevar{prefix}. Of course, you also have to ensure that these
-directories are in Python's module search path, such as by putting a
-\file{.pth} file in \filevar{prefix}. See section~\ref{search-path}
-to find out how to modify Python's search path.
-
-If you want to define an entire installation scheme, you just have to
-supply all of the installation directory options. The recommended way
-to do this is to supply relative paths; for example, if you want to
-maintain all Python module-related files under \file{python} in your
-home directory, and you want a separate directory for each platform that
-you use your home directory from, you might define the following
-installation scheme:
-
-\begin{verbatim}
-python setup.py install --home=~ \
- --install-purelib=python/lib \
- --install-platlib=python/lib.$PLAT \
- --install-scripts=python/scripts
- --install-data=python/data
-\end{verbatim}
-% $ % -- bow to font-lock
-
-or, equivalently,
-
-\begin{verbatim}
-python setup.py install --home=~/python \
- --install-purelib=lib \
- --install-platlib='lib.$PLAT' \
- --install-scripts=scripts
- --install-data=data
-\end{verbatim}
-% $ % -- bow to font-lock
-
-\code{\$PLAT} is not (necessarily) an environment variable---it will be
-expanded by the Distutils as it parses your command line options, just
-as it does when parsing your configuration file(s).
-
-Obviously, specifying the entire installation scheme every time you
-install a new module distribution would be very tedious. Thus, you can
-put these options into your Distutils config file (see
-section~\ref{config-files}):
-
-\begin{verbatim}
-[install]
-install-base=$HOME
-install-purelib=python/lib
-install-platlib=python/lib.$PLAT
-install-scripts=python/scripts
-install-data=python/data
-\end{verbatim}
-
-or, equivalently,
-
-\begin{verbatim}
-[install]
-install-base=$HOME/python
-install-purelib=lib
-install-platlib=lib.$PLAT
-install-scripts=scripts
-install-data=data
-\end{verbatim}
-
-Note that these two are \emph{not} equivalent if you supply a different
-installation base directory when you run the setup script. For example,
-
-\begin{verbatim}
-python setup.py --install-base=/tmp
-\end{verbatim}
-
-would install pure modules to \filevar{/tmp/python/lib} in the first
-case, and to \filevar{/tmp/lib} in the second case. (For the second
-case, you probably want to supply an installation base of
-\file{/tmp/python}.)
-
-You probably noticed the use of \code{\$HOME} and \code{\$PLAT} in the
-sample configuration file input. These are Distutils configuration
-variables, which bear a strong resemblance to environment variables.
-In fact, you can use environment variables in config files on
-platforms that have such a notion but the Distutils additionally
-define a few extra variables that may not be in your environment, such
-as \code{\$PLAT}. (And of course, on systems that don't have
-environment variables, such as Mac OS 9, the configuration
-variables supplied by the Distutils are the only ones you can use.)
-See section~\ref{config-files} for details.
-
-% XXX need some Windows and Mac OS examples---when would custom
-% installation schemes be needed on those platforms?
-
-
-% XXX I'm not sure where this section should go.
-\subsection{Modifying Python's Search Path}
-\label{search-path}
-
-When the Python interpreter executes an \keyword{import} statement, it
-searches for both Python code and extension modules along a search
-path. A default value for the path is configured into the Python
-binary when the interpreter is built. You can determine the path by
-importing the \module{sys} module and printing the value of
-\code{sys.path}.
-
-\begin{verbatim}
-$ python
-Python 2.2 (#11, Oct 3 2002, 13:31:27)
-[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2
-Type ``help'', ``copyright'', ``credits'' or ``license'' for more information.
->>> import sys
->>> sys.path
-['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2',
- '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload',
- '/usr/local/lib/python2.3/site-packages']
->>>
-\end{verbatim}
-
-The null string in \code{sys.path} represents the current working
-directory.
-
-The expected convention for locally installed packages is to put them
-in the \file{.../site-packages/} directory, but you may want to
-install Python modules into some arbitrary directory. For example,
-your site may have a convention of keeping all software related to the
-web server under \file{/www}. Add-on Python modules might then belong
-in \file{/www/python}, and in order to import them, this directory
-must be added to \code{sys.path}. There are several different ways to
-add the directory.
-
-The most convenient way is to add a path configuration file to a
-directory that's already on Python's path, usually to the
-\file{.../site-packages/} directory. Path configuration files have an
-extension of \file{.pth}, and each line must contain a single path
-that will be appended to \code{sys.path}. (Because the new paths are
-appended to \code{sys.path}, modules in the added directories will not
-override standard modules. This means you can't use this mechanism
-for installing fixed versions of standard modules.)
-
-Paths can be absolute or relative, in which case they're relative to
-the directory containing the \file{.pth} file. Any directories added
-to the search path will be scanned in turn for \file{.pth} files. See
-\citetitle[http://www.python.org/dev/doc/devel/lib/module-site.html]{the
-documentation for the \module{site} module} for more information.
-
-A slightly less convenient way is to edit the \file{site.py} file in
-Python's standard library, and modify \code{sys.path}. \file{site.py}
-is automatically imported when the Python interpreter is executed,
-unless the \programopt{-S} switch is supplied to suppress this
-behaviour. So you could simply edit \file{site.py} and add two lines to it:
-
-\begin{verbatim}
-import sys
-sys.path.append('/www/python/')
-\end{verbatim}
-
-However, if you reinstall the same major version of Python (perhaps
-when upgrading from 2.2 to 2.2.2, for example) \file{site.py} will be
-overwritten by the stock version. You'd have to remember that it was
-modified and save a copy before doing the installation.
-
-There are two environment variables that can modify \code{sys.path}.
-\envvar{PYTHONHOME} sets an alternate value for the prefix of the
-Python installation. For example, if \envvar{PYTHONHOME} is set to
-\samp{/www/python}, the search path will be set to \code{['',
-'/www/python/lib/python2.2/', '/www/python/lib/python2.3/plat-linux2',
-...]}.
-
-The \envvar{PYTHONPATH} variable can be set to a list of paths that
-will be added to the beginning of \code{sys.path}. For example, if
-\envvar{PYTHONPATH} is set to \samp{/www/python:/opt/py}, the search
-path will begin with \code{['/www/python', '/opt/py']}. (Note that
-directories must exist in order to be added to \code{sys.path}; the
-\module{site} module removes paths that don't exist.)
-
-Finally, \code{sys.path} is just a regular Python list, so any Python
-application can modify it by adding or removing entries.
-
-
-\section{Distutils Configuration Files}
-\label{config-files}
-
-As mentioned above, you can use Distutils configuration files to record
-personal or site preferences for any Distutils options. That is, any
-option to any command can be stored in one of two or three (depending on
-your platform) configuration files, which will be consulted before the
-command-line is parsed. This means that configuration files will
-override default values, and the command-line will in turn override
-configuration files. Furthermore, if multiple configuration files
-apply, values from ``earlier'' files are overridden by ``later'' files.
-
-
-\subsection{Location and names of config files}
-\label{config-filenames}
-
-The names and locations of the configuration files vary slightly across
-platforms. On \UNIX, the three configuration files (in the order they
-are processed) are:
-\begin{tableiii}{l|l|c}{textrm}
- {Type of file}{Location and filename}{Notes}
- \lineiii{system}{\filenq{\filevar{prefix}/lib/python\filevar{ver}/distutils/distutils.cfg}}{(1)}
- \lineiii{personal}{\filenq{\$HOME/.pydistutils.cfg}}{(2)}
- \lineiii{local}{\filenq{setup.cfg}}{(3)}
-\end{tableiii}
-
-On Windows, the configuration files are:
-\begin{tableiii}{l|l|c}{textrm}
- {Type of file}{Location and filename}{Notes}
- \lineiii{system}{\filenq{\filevar{prefix}\textbackslash{}Lib\textbackslash{}distutils\textbackslash{}distutils.cfg}}{(4)}
- \lineiii{personal}{\filenq{\%HOME\%\textbackslash{}pydistutils.cfg}}{(5)}
- \lineiii{local}{\filenq{setup.cfg}}{(3)}
-\end{tableiii}
-
-And on Mac OS, they are:
-\begin{tableiii}{l|l|c}{textrm}
- {Type of file}{Location and filename}{Notes}
- \lineiii{system}{\filenq{\filevar{prefix}:Lib:distutils:distutils.cfg}}{(6)}
- \lineiii{personal}{N/A}{}
- \lineiii{local}{\filenq{setup.cfg}}{(3)}
-\end{tableiii}
-
-\noindent Notes:
-\begin{description}
-\item[(1)] Strictly speaking, the system-wide configuration file lives
- in the directory where the Distutils are installed; under Python 1.6
- and later on \UNIX, this is as shown. For Python 1.5.2, the Distutils
- will normally be installed to
- \file{\filevar{prefix}/lib/site-packages/python1.5/distutils},
- so the system configuration file should be put there under Python
- 1.5.2.
-\item[(2)] On \UNIX, if the \envvar{HOME} environment variable is not
- defined, the user's home directory will be determined with the
- \function{getpwuid()} function from the standard
- \ulink{\module{pwd}}{../lib/module-pwd.html} module.
-\item[(3)] I.e., in the current directory (usually the location of the
- setup script).
-\item[(4)] (See also note (1).) Under Python 1.6 and later, Python's
- default ``installation prefix'' is \file{C:\textbackslash{}Python}, so
- the system configuration file is normally
- \file{C:\textbackslash{}Python\textbackslash{}Lib\textbackslash{}distutils\textbackslash{}distutils.cfg}.
- Under Python 1.5.2, the default prefix was
- \file{C:\textbackslash{}Program~Files\textbackslash{}Python}, and the
- Distutils were not part of the standard library---so the system
- configuration file would be
- \file{C:\textbackslash{}Program~Files\textbackslash{}Python\textbackslash{}distutils\textbackslash{}distutils.cfg}
- in a standard Python 1.5.2 installation under Windows.
-\item[(5)] On Windows, if the \envvar{HOME} environment variable is not
- defined, no personal configuration file will be found or used. (In
- other words, the Distutils make no attempt to guess your home
- directory on Windows.)
-\item[(6)] (See also notes (1) and (4).) The default installation
- prefix is just \file{Python:}, so under Python 1.6 and later this is
- normally\file{Python:Lib:distutils:distutils.cfg}.
-\end{description}
-
-
-\subsection{Syntax of config files}
-\label{config-syntax}
-
-The Distutils configuration files all have the same syntax. The config
-files are grouped into sections. There is one section for each Distutils
-command, plus a \code{global} section for global options that affect
-every command. Each section consists of one option per line, specified
-as \code{option=value}.
-
-For example, the following is a complete config file that just forces
-all commands to run quietly by default:
-
-\begin{verbatim}
-[global]
-verbose=0
-\end{verbatim}
-
-If this is installed as the system config file, it will affect all
-processing of any Python module distribution by any user on the current
-system. If it is installed as your personal config file (on systems
-that support them), it will affect only module distributions processed
-by you. And if it is used as the \file{setup.cfg} for a particular
-module distribution, it affects only that distribution.
-
-You could override the default ``build base'' directory and make the
-\command{build*} commands always forcibly rebuild all files with the
-following:
-
-\begin{verbatim}
-[build]
-build-base=blib
-force=1
-\end{verbatim}
-
-which corresponds to the command-line arguments
-
-\begin{verbatim}
-python setup.py build --build-base=blib --force
-\end{verbatim}
-
-except that including the \command{build} command on the command-line
-means that command will be run. Including a particular command in
-config files has no such implication; it only means that if the command
-is run, the options in the config file will apply. (Or if other
-commands that derive values from it are run, they will use the values in
-the config file.)
-
-You can find out the complete list of options for any command using the
-\longprogramopt{help} option, e.g.:
-
-\begin{verbatim}
-python setup.py build --help
-\end{verbatim}
-
-and you can find out the complete list of global options by using
-\longprogramopt{help} without a command:
-
-\begin{verbatim}
-python setup.py --help
-\end{verbatim}
-
-See also the ``Reference'' section of the ``Distributing Python
-Modules'' manual.
-
-\section{Building Extensions: Tips and Tricks}
-\label{building-ext}
-
-Whenever possible, the Distutils try to use the configuration
-information made available by the Python interpreter used to run the
-\file{setup.py} script. For example, the same compiler and linker
-flags used to compile Python will also be used for compiling
-extensions. Usually this will work well, but in complicated
-situations this might be inappropriate. This section discusses how to
-override the usual Distutils behaviour.
-
-\subsection{Tweaking compiler/linker flags}
-\label{tweak-flags}
-
-Compiling a Python extension written in C or \Cpp will sometimes
-require specifying custom flags for the compiler and linker in order
-to use a particular library or produce a special kind of object code.
-This is especially true if the extension hasn't been tested on your
-platform, or if you're trying to cross-compile Python.
-
-In the most general case, the extension author might have foreseen
-that compiling the extensions would be complicated, and provided a
-\file{Setup} file for you to edit. This will likely only be done if
-the module distribution contains many separate extension modules, or
-if they often require elaborate sets of compiler flags in order to work.
-
-A \file{Setup} file, if present, is parsed in order to get a list of
-extensions to build. Each line in a \file{Setup} describes a single
-module. Lines have the following structure:
-
-\begin{alltt}
-\var{module} ... [\var{sourcefile} ...] [\var{cpparg} ...] [\var{library} ...]
-\end{alltt}
-
-Let's examine each of the fields in turn.
-
-\begin{itemize}
-
-\item \var{module} is the name of the extension module to be built,
- and should be a valid Python identifier. You can't just change
- this in order to rename a module (edits to the source code would
- also be needed), so this should be left alone.
-
-\item \var{sourcefile} is anything that's likely to be a source code
- file, at least judging by the filename. Filenames ending in
- \file{.c} are assumed to be written in C, filenames ending in
- \file{.C}, \file{.cc}, and \file{.c++} are assumed to be
- \Cpp, and filenames ending in \file{.m} or \file{.mm} are
- assumed to be in Objective C.
-
-\item \var{cpparg} is an argument for the C preprocessor,
- and is anything starting with \programopt{-I}, \programopt{-D},
- \programopt{-U} or \programopt{-C}.
-
-\item \var{library} is anything ending in \file{.a} or beginning with
- \programopt{-l} or \programopt{-L}.
-\end{itemize}
-
-If a particular platform requires a special library on your platform,
-you can add it by editing the \file{Setup} file and running
-\code{python setup.py build}. For example, if the module defined by the line
-
-\begin{verbatim}
-foo foomodule.c
-\end{verbatim}
-
-must be linked with the math library \file{libm.a} on your platform,
-simply add \programopt{-lm} to the line:
-
-\begin{verbatim}
-foo foomodule.c -lm
-\end{verbatim}
-
-Arbitrary switches intended for the compiler or the linker can be
-supplied with the \programopt{-Xcompiler} \var{arg} and
-\programopt{-Xlinker} \var{arg} options:
-
-\begin{verbatim}
-foo foomodule.c -Xcompiler -o32 -Xlinker -shared -lm
-\end{verbatim}
-
-The next option after \programopt{-Xcompiler} and
-\programopt{-Xlinker} will be appended to the proper command line, so
-in the above example the compiler will be passed the \programopt{-o32}
-option, and the linker will be passed \programopt{-shared}. If a
-compiler option requires an argument, you'll have to supply multiple
-\programopt{-Xcompiler} options; for example, to pass \code{-x c++} the
-\file{Setup} file would have to contain
-\code{-Xcompiler -x -Xcompiler c++}.
-
-Compiler flags can also be supplied through setting the
-\envvar{CFLAGS} environment variable. If set, the contents of
-\envvar{CFLAGS} will be added to the compiler flags specified in the
-\file{Setup} file.
-
-
-\subsection{Using non-Microsoft compilers on Windows \label{non-ms-compilers}}
-\sectionauthor{Rene Liebscher}{R.Liebscher@gmx.de}
-
-\subsubsection{Borland C++}
-
-This subsection describes the necessary steps to use Distutils with the
-Borland \Cpp{} compiler version 5.5.
-%Should we mention that users have to create cfg-files for the compiler?
-%see also http://community.borland.com/article/0,1410,21205,00.html
-
-First you have to know that Borland's object file format (OMF) is
-different from the format used by the Python version you can download
-from the Python or ActiveState Web site. (Python is built with
-Microsoft Visual \Cpp, which uses COFF as the object file format.)
-For this reason you have to convert Python's library
-\file{python20.lib} into the Borland format. You can do this as
-follows:
-
-\begin{verbatim}
-coff2omf python20.lib python20_bcpp.lib
-\end{verbatim}
-
-The \file{coff2omf} program comes with the Borland compiler. The file
-\file{python20.lib} is in the \file{Libs} directory of your Python
-installation. If your extension uses other libraries (zlib,...) you
-have to convert them too.
-
-The converted files have to reside in the same directories as the
-normal libraries.
-
-How does Distutils manage to use these libraries with their changed
-names? If the extension needs a library (eg. \file{foo}) Distutils
-checks first if it finds a library with suffix \file{_bcpp}
-(eg. \file{foo_bcpp.lib}) and then uses this library. In the case it
-doesn't find such a special library it uses the default name
-(\file{foo.lib}.)\footnote{This also means you could replace all
-existing COFF-libraries with OMF-libraries of the same name.}
-
-To let Distutils compile your extension with Borland \Cpp{} you now have
-to type:
-
-\begin{verbatim}
-python setup.py build --compiler=bcpp
-\end{verbatim}
-
-If you want to use the Borland \Cpp{} compiler as the default, you
-could specify this in your personal or system-wide configuration file
-for Distutils (see section~\ref{config-files}.)
-
-\begin{seealso}
- \seetitle[http://www.borland.com/bcppbuilder/freecompiler/]
- {\Cpp{}Builder Compiler}
- {Information about the free \Cpp{} compiler from Borland,
- including links to the download pages.}
-
- \seetitle[http://www.cyberus.ca/\~{}g_will/pyExtenDL.shtml]
- {Creating Python Extensions Using Borland's Free Compiler}
- {Document describing how to use Borland's free command-line C++
- compiler to build Python.}
-\end{seealso}
-
-
-\subsubsection{GNU C / Cygwin / MinGW}
-
-This section describes the necessary steps to use Distutils with the
-GNU C/\Cpp{} compilers in their Cygwin and MinGW
-distributions.\footnote{Check
-\url{http://sources.redhat.com/cygwin/} and
-\url{http://www.mingw.org/} for more information}
-For a Python interpreter that was built with Cygwin, everything should
-work without any of these following steps.
-
-These compilers require some special libraries.
-This task is more complex than for Borland's \Cpp, because there is no
-program to convert the library.
-% I don't understand what the next line means. --amk
-% (inclusive the references on data structures.)
-
-First you have to create a list of symbols which the Python DLL exports.
-(You can find a good program for this task at
-\url{http://starship.python.net/crew/kernr/mingw32/Notes.html}, see at
-PExports 0.42h there.)
-
-\begin{verbatim}
-pexports python20.dll >python20.def
-\end{verbatim}
-
-Then you can create from these information an import library for gcc.
-
-\begin{verbatim}
-dlltool --dllname python20.dll --def python20.def --output-lib libpython20.a
-\end{verbatim}
-
-The resulting library has to be placed in the same directory as
-\file{python20.lib}. (Should be the \file{libs} directory under your
-Python installation directory.)
-
-If your extension uses other libraries (zlib,...) you might
-have to convert them too.
-The converted files have to reside in the same directories as the normal
-libraries do.
-
-To let Distutils compile your extension with Cygwin you now have to type
-
-\begin{verbatim}
-python setup.py build --compiler=cygwin
-\end{verbatim}
-
-and for Cygwin in no-cygwin mode\footnote{Then you have no
-\POSIX{} emulation available, but you also don't need
-\file{cygwin1.dll}.} or for MinGW type:
-
-\begin{verbatim}
-python setup.py build --compiler=mingw32
-\end{verbatim}
-
-If you want to use any of these options/compilers as default, you should
-consider to write it in your personal or system-wide configuration file
-for Distutils (see section~\ref{config-files}.)
-
-\begin{seealso}
- \seetitle[http://www.zope.org/Members/als/tips/win32_mingw_modules]
- {Building Python modules on MS Windows platform with MinGW}
- {Information about building the required libraries for the MinGW
- environment.}
-
- \seeurl{http://pyopengl.sourceforge.net/ftp/win32-stuff/}
- {Converted import libraries in Cygwin/MinGW and Borland format,
- and a script to create the registry entries needed for Distutils
- to locate the built Python.}
-\end{seealso}
-
-
-
-\end{document}
diff --git a/Doc/isilo/.cvsignore b/Doc/isilo/.cvsignore
deleted file mode 100644
index b42e18fb78..0000000000
--- a/Doc/isilo/.cvsignore
+++ /dev/null
@@ -1,11 +0,0 @@
-api
-doc
-ext
-lib
-mac
-ref
-tut
-dist
-inst
-whatsnew
-python-*.pdb
diff --git a/Doc/lib/.cvsignore b/Doc/lib/.cvsignore
deleted file mode 100644
index ea4fca3aac..0000000000
--- a/Doc/lib/.cvsignore
+++ /dev/null
@@ -1,3 +0,0 @@
-*.esis
-*.esis1
-*.xml
diff --git a/Doc/lib/asttable.tex b/Doc/lib/asttable.tex
deleted file mode 100644
index 7f6ba9f7b4..0000000000
--- a/Doc/lib/asttable.tex
+++ /dev/null
@@ -1,253 +0,0 @@
-\begin{longtableiii}{lll}{class}{Node type}{Attribute}{Value}
-
-\lineiii{Add}{\member{left}}{left operand}
-\lineiii{}{\member{right}}{right operand}
-\hline
-
-\lineiii{And}{\member{nodes}}{list of operands}
-\hline
-
-\lineiii{AssAttr}{}{\emph{attribute as target of assignment}}
-\lineiii{}{\member{expr}}{expression on the left-hand side of the dot}
-\lineiii{}{\member{attrname}}{the attribute name, a string}
-\lineiii{}{\member{flags}}{XXX}
-\hline
-
-\lineiii{AssList}{\member{nodes}}{list of list elements being assigned to}
-\hline
-
-\lineiii{AssName}{\member{name}}{name being assigned to}
-\lineiii{}{\member{flags}}{XXX}
-\hline
-
-\lineiii{AssTuple}{\member{nodes}}{list of tuple elements being assigned to}
-\hline
-
-\lineiii{Assert}{\member{test}}{the expression to be tested}
-\lineiii{}{\member{fail}}{the value of the \exception{AssertionError}}
-\hline
-
-\lineiii{Assign}{\member{nodes}}{a list of assignment targets, one per equal sign}
-\lineiii{}{\member{expr}}{the value being assigned}
-\hline
-
-\lineiii{AugAssign}{\member{node}}{}
-\lineiii{}{\member{op}}{}
-\lineiii{}{\member{expr}}{}
-\hline
-
-\lineiii{Backquote}{\member{expr}}{}
-\hline
-
-\lineiii{Bitand}{\member{nodes}}{}
-\hline
-
-\lineiii{Bitor}{\member{nodes}}{}
-\hline
-
-\lineiii{Bitxor}{\member{nodes}}{}
-\hline
-
-\lineiii{Break}{}{}
-\hline
-
-\lineiii{CallFunc}{\member{node}}{expression for the callee}
-\lineiii{}{\member{args}}{a list of arguments}
-\lineiii{}{\member{star_args}}{the extended *-arg value}
-\lineiii{}{\member{dstar_args}}{the extended **-arg value}
-\hline
-
-\lineiii{Class}{\member{name}}{the name of the class, a string}
-\lineiii{}{\member{bases}}{a list of base classes}
-\lineiii{}{\member{doc}}{doc string, a string or \code{None}}
-\lineiii{}{\member{code}}{the body of the class statement}
-\hline
-
-\lineiii{Compare}{\member{expr}}{}
-\lineiii{}{\member{ops}}{}
-\hline
-
-\lineiii{Const}{\member{value}}{}
-\hline
-
-\lineiii{Continue}{}{}
-\hline
-
-\lineiii{Dict}{\member{items}}{}
-\hline
-
-\lineiii{Discard}{\member{expr}}{}
-\hline
-
-\lineiii{Div}{\member{left}}{}
-\lineiii{}{\member{right}}{}
-\hline
-
-\lineiii{Ellipsis}{}{}
-\hline
-
-\lineiii{Exec}{\member{expr}}{}
-\lineiii{}{\member{locals}}{}
-\lineiii{}{\member{globals}}{}
-\hline
-
-\lineiii{For}{\member{assign}}{}
-\lineiii{}{\member{list}}{}
-\lineiii{}{\member{body}}{}
-\lineiii{}{\member{else_}}{}
-\hline
-
-\lineiii{From}{\member{modname}}{}
-\lineiii{}{\member{names}}{}
-\hline
-
-\lineiii{Function}{\member{name}}{name used in def, a string}
-\lineiii{}{\member{argnames}}{list of argument names, as strings}
-\lineiii{}{\member{defaults}}{list of default values}
-\lineiii{}{\member{flags}}{xxx}
-\lineiii{}{\member{doc}}{doc string, a string or \code{None}}
-\lineiii{}{\member{code}}{the body of the function}
-\hline
-
-\lineiii{Getattr}{\member{expr}}{}
-\lineiii{}{\member{attrname}}{}
-\hline
-
-\lineiii{Global}{\member{names}}{}
-\hline
-
-\lineiii{If}{\member{tests}}{}
-\lineiii{}{\member{else_}}{}
-\hline
-
-\lineiii{Import}{\member{names}}{}
-\hline
-
-\lineiii{Invert}{\member{expr}}{}
-\hline
-
-\lineiii{Keyword}{\member{name}}{}
-\lineiii{}{\member{expr}}{}
-\hline
-
-\lineiii{Lambda}{\member{argnames}}{}
-\lineiii{}{\member{defaults}}{}
-\lineiii{}{\member{flags}}{}
-\lineiii{}{\member{code}}{}
-\hline
-
-\lineiii{LeftShift}{\member{left}}{}
-\lineiii{}{\member{right}}{}
-\hline
-
-\lineiii{List}{\member{nodes}}{}
-\hline
-
-\lineiii{ListComp}{\member{expr}}{}
-\lineiii{}{\member{quals}}{}
-\hline
-
-\lineiii{ListCompFor}{\member{assign}}{}
-\lineiii{}{\member{list}}{}
-\lineiii{}{\member{ifs}}{}
-\hline
-
-\lineiii{ListCompIf}{\member{test}}{}
-\hline
-
-\lineiii{Mod}{\member{left}}{}
-\lineiii{}{\member{right}}{}
-\hline
-
-\lineiii{Module}{\member{doc}}{doc string, a string or \code{None}}
-\lineiii{}{\member{node}}{body of the module, a \class{Stmt}}
-\hline
-
-\lineiii{Mul}{\member{left}}{}
-\lineiii{}{\member{right}}{}
-\hline
-
-\lineiii{Name}{\member{name}}{}
-\hline
-
-\lineiii{Not}{\member{expr}}{}
-\hline
-
-\lineiii{Or}{\member{nodes}}{}
-\hline
-
-\lineiii{Pass}{}{}
-\hline
-
-\lineiii{Power}{\member{left}}{}
-\lineiii{}{\member{right}}{}
-\hline
-
-\lineiii{Print}{\member{nodes}}{}
-\lineiii{}{\member{dest}}{}
-\hline
-
-\lineiii{Printnl}{\member{nodes}}{}
-\lineiii{}{\member{dest}}{}
-\hline
-
-\lineiii{Raise}{\member{expr1}}{}
-\lineiii{}{\member{expr2}}{}
-\lineiii{}{\member{expr3}}{}
-\hline
-
-\lineiii{Return}{\member{value}}{}
-\hline
-
-\lineiii{RightShift}{\member{left}}{}
-\lineiii{}{\member{right}}{}
-\hline
-
-\lineiii{Slice}{\member{expr}}{}
-\lineiii{}{\member{flags}}{}
-\lineiii{}{\member{lower}}{}
-\lineiii{}{\member{upper}}{}
-\hline
-
-\lineiii{Sliceobj}{\member{nodes}}{list of statements}
-\hline
-
-\lineiii{Stmt}{\member{nodes}}{}
-\hline
-
-\lineiii{Sub}{\member{left}}{}
-\lineiii{}{\member{right}}{}
-\hline
-
-\lineiii{Subscript}{\member{expr}}{}
-\lineiii{}{\member{flags}}{}
-\lineiii{}{\member{subs}}{}
-\hline
-
-\lineiii{TryExcept}{\member{body}}{}
-\lineiii{}{\member{handlers}}{}
-\lineiii{}{\member{else_}}{}
-\hline
-
-\lineiii{TryFinally}{\member{body}}{}
-\lineiii{}{\member{final}}{}
-\hline
-
-\lineiii{Tuple}{\member{nodes}}{}
-\hline
-
-\lineiii{UnaryAdd}{\member{expr}}{}
-\hline
-
-\lineiii{UnarySub}{\member{expr}}{}
-\hline
-
-\lineiii{While}{\member{test}}{}
-\lineiii{}{\member{body}}{}
-\lineiii{}{\member{else_}}{}
-\hline
-
-\lineiii{Yield}{\member{value}}{}
-\hline
-
-\end{longtableiii}
diff --git a/Doc/lib/caseless.py b/Doc/lib/caseless.py
deleted file mode 100755
index 107fed68e3..0000000000
--- a/Doc/lib/caseless.py
+++ /dev/null
@@ -1,62 +0,0 @@
-from optparse import Option, OptionParser, _match_abbrev
-
-# This case-insensitive option parser relies on having a
-# case-insensitive dictionary type available. Here's one
-# for Python 2.2. Note that a *real* case-insensitive
-# dictionary type would also have to implement __new__(),
-# update(), and setdefault() -- but that's not the point
-# of this exercise.
-
-class caseless_dict (dict):
- def __setitem__ (self, key, value):
- dict.__setitem__(self, key.lower(), value)
-
- def __getitem__ (self, key):
- return dict.__getitem__(self, key.lower())
-
- def get (self, key, default=None):
- return dict.get(self, key.lower())
-
- def has_key (self, key):
- return dict.has_key(self, key.lower())
-
-
-class CaselessOptionParser (OptionParser):
-
- def _create_option_list (self):
- self.option_list = []
- self._short_opt = caseless_dict()
- self._long_opt = caseless_dict()
- self._long_opts = []
- self.defaults = {}
-
- def _match_long_opt (self, opt):
- return _match_abbrev(opt.lower(), self._long_opt.keys())
-
-
-if __name__ == "__main__":
- from optik.errors import OptionConflictError
-
- # test 1: no options to start with
- parser = CaselessOptionParser()
- try:
- parser.add_option("-H", dest="blah")
- except OptionConflictError:
- print "ok: got OptionConflictError for -H"
- else:
- print "not ok: no conflict between -h and -H"
-
- parser.add_option("-f", "--file", dest="file")
- #print `parser.get_option("-f")`
- #print `parser.get_option("-F")`
- #print `parser.get_option("--file")`
- #print `parser.get_option("--fIlE")`
- (options, args) = parser.parse_args(["--FiLe", "foo"])
- assert options.file == "foo", options.file
- print "ok: case insensitive long options work"
-
- (options, args) = parser.parse_args(["-F", "bar"])
- assert options.file == "bar", options.file
- print "ok: case insensitive short options work"
-
-
diff --git a/Doc/lib/compiler.tex b/Doc/lib/compiler.tex
deleted file mode 100644
index 0c7c06dddb..0000000000
--- a/Doc/lib/compiler.tex
+++ /dev/null
@@ -1,351 +0,0 @@
-\chapter{Python compiler package \label{compiler}}
-
-\sectionauthor{Jeremy Hylton}{jeremy@zope.com}
-
-
-The Python compiler package is a tool for analyzing Python source code
-and generating Python bytecode. The compiler contains libraries to
-generate an abstract syntax tree from Python source code and to
-generate Python bytecode from the tree.
-
-The \refmodule{compiler} package is a Python source to bytecode
-translator written in Python. It uses the built-in parser and
-standard \refmodule{parser} module to generated a concrete syntax
-tree. This tree is used to generate an abstract syntax tree (AST) and
-then Python bytecode.
-
-The full functionality of the package duplicates the builtin compiler
-provided with the Python interpreter. It is intended to match its
-behavior almost exactly. Why implement another compiler that does the
-same thing? The package is useful for a variety of purposes. It can
-be modified more easily than the builtin compiler. The AST it
-generates is useful for analyzing Python source code.
-
-This chapter explains how the various components of the
-\refmodule{compiler} package work. It blends reference material with
-a tutorial.
-
-The following modules are part of the \refmodule{compiler} package:
-
-\localmoduletable
-
-
-\section{The basic interface}
-
-\declaremodule{}{compiler}
-
-The top-level of the package defines four functions. If you import
-\module{compiler}, you will get these functions and a collection of
-modules contained in the package.
-
-\begin{funcdesc}{parse}{buf}
-Returns an abstract syntax tree for the Python source code in \var{buf}.
-The function raises SyntaxError if there is an error in the source
-code. The return value is a \class{compiler.ast.Module} instance that
-contains the tree.
-\end{funcdesc}
-
-\begin{funcdesc}{parseFile}{path}
-Return an abstract syntax tree for the Python source code in the file
-specified by \var{path}. It is equivalent to
-\code{parse(open(\var{path}).read())}.
-\end{funcdesc}
-
-\begin{funcdesc}{walk}{ast, visitor\optional{, verbose}}
-Do a pre-order walk over the abstract syntax tree \var{ast}. Call the
-appropriate method on the \var{visitor} instance for each node
-encountered.
-\end{funcdesc}
-
-\begin{funcdesc}{compile}{source, filename, mode, flags=None,
- dont_inherit=None}
-Compile the string \var{source}, a Python module, statement or
-expression, into a code object that can be executed by the exec
-statement or \function{eval()}. This function is a replacement for the
-built-in \function{compile()} function.
-
-The \var{filename} will be used for run-time error messages.
-
-The \var{mode} must be 'exec' to compile a module, 'single' to compile a
-single (interactive) statement, or 'eval' to compile an expression.
-
-The \var{flags} and \var{dont_inherit} arguments affect future-related
-statements, but are not supported yet.
-\end{funcdesc}
-
-\begin{funcdesc}{compileFile}{source}
-Compiles the file \var{source} and generates a .pyc file.
-\end{funcdesc}
-
-The \module{compiler} package contains the following modules:
-\refmodule[compiler.ast]{ast}, \module{consts}, \module{future},
-\module{misc}, \module{pyassem}, \module{pycodegen}, \module{symbols},
-\module{transformer}, and \refmodule[compiler.visitor]{visitor}.
-
-\section{Limitations}
-
-There are some problems with the error checking of the compiler
-package. The interpreter detects syntax errors in two distinct
-phases. One set of errors is detected by the interpreter's parser,
-the other set by the compiler. The compiler package relies on the
-interpreter's parser, so it get the first phases of error checking for
-free. It implements the second phase itself, and that implement is
-incomplete. For example, the compiler package does not raise an error
-if a name appears more than once in an argument list:
-\code{def f(x, x): ...}
-
-A future version of the compiler should fix these problems.
-
-\section{Python Abstract Syntax}
-
-The \module{compiler.ast} module defines an abstract syntax for
-Python. In the abstract syntax tree, each node represents a syntactic
-construct. The root of the tree is \class{Module} object.
-
-The abstract syntax offers a higher level interface to parsed Python
-source code. The \ulink{\module{parser}}
-{http://www.python.org/doc/current/lib/module-parser.html}
-module and the compiler written in C for the Python interpreter use a
-concrete syntax tree. The concrete syntax is tied closely to the
-grammar description used for the Python parser. Instead of a single
-node for a construct, there are often several levels of nested nodes
-that are introduced by Python's precedence rules.
-
-The abstract syntax tree is created by the
-\module{compiler.transformer} module. The transformer relies on the
-builtin Python parser to generate a concrete syntax tree. It
-generates an abstract syntax tree from the concrete tree.
-
-The \module{transformer} module was created by Greg
-Stein\index{Stein, Greg} and Bill Tutt\index{Tutt, Bill} for an
-experimental Python-to-C compiler. The current version contains a
-number of modifications and improvements, but the basic form of the
-abstract syntax and of the transformer are due to Stein and Tutt.
-
-\subsection{AST Nodes}
-
-\declaremodule{}{compiler.ast}
-
-The \module{compiler.ast} module is generated from a text file that
-describes each node type and its elements. Each node type is
-represented as a class that inherits from the abstract base class
-\class{compiler.ast.Node} and defines a set of named attributes for
-child nodes.
-
-\begin{classdesc}{Node}{}
-
- The \class{Node} instances are created automatically by the parser
- generator. The recommended interface for specific \class{Node}
- instances is to use the public attributes to access child nodes. A
- public attribute may be bound to a single node or to a sequence of
- nodes, depending on the \class{Node} type. For example, the
- \member{bases} attribute of the \class{Class} node, is bound to a
- list of base class nodes, and the \member{doc} attribute is bound to
- a single node.
-
- Each \class{Node} instance has a \member{lineno} attribute which may
- be \code{None}. XXX Not sure what the rules are for which nodes
- will have a useful lineno.
-\end{classdesc}
-
-All \class{Node} objects offer the following methods:
-
-\begin{methoddesc}{getChildren}{}
- Returns a flattened list of the child nodes and objects in the
- order they occur. Specifically, the order of the nodes is the
- order in which they appear in the Python grammar. Not all of the
- children are \class{Node} instances. The names of functions and
- classes, for example, are plain strings.
-\end{methoddesc}
-
-\begin{methoddesc}{getChildNodes}{}
- Returns a flattened list of the child nodes in the order they
- occur. This method is like \method{getChildren()}, except that it
- only returns those children that are \class{Node} instances.
-\end{methoddesc}
-
-Two examples illustrate the general structure of \class{Node}
-classes. The \keyword{while} statement is defined by the following
-grammar production:
-
-\begin{verbatim}
-while_stmt: "while" expression ":" suite
- ["else" ":" suite]
-\end{verbatim}
-
-The \class{While} node has three attributes: \member{test},
-\member{body}, and \member{else_}. (If the natural name for an
-attribute is also a Python reserved word, it can't be used as an
-attribute name. An underscore is appended to the word to make it a
-legal identifier, hence \member{else_} instead of \keyword{else}.)
-
-The \keyword{if} statement is more complicated because it can include
-several tests.
-
-\begin{verbatim}
-if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
-\end{verbatim}
-
-The \class{If} node only defines two attributes: \member{tests} and
-\member{else_}. The \member{tests} attribute is a sequence of test
-expression, consequent body pairs. There is one pair for each
-\keyword{if}/\keyword{elif} clause. The first element of the pair is
-the test expression. The second elements is a \class{Stmt} node that
-contains the code to execute if the test is true.
-
-The \method{getChildren()} method of \class{If} returns a flat list of
-child nodes. If there are three \keyword{if}/\keyword{elif} clauses
-and no \keyword{else} clause, then \method{getChildren()} will return
-a list of six elements: the first test expression, the first
-\class{Stmt}, the second text expression, etc.
-
-The following table lists each of the \class{Node} subclasses defined
-in \module{compiler.ast} and each of the public attributes available
-on their instances. The values of most of the attributes are
-themselves \class{Node} instances or sequences of instances. When the
-value is something other than an instance, the type is noted in the
-comment. The attributes are listed in the order in which they are
-returned by \method{getChildren()} and \method{getChildNodes()}.
-
-\input{asttable}
-
-
-\subsection{Assignment nodes}
-
-There is a collection of nodes used to represent assignments. Each
-assignment statement in the source code becomes a single
-\class{Assign} node in the AST. The \member{nodes} attribute is a
-list that contains a node for each assignment target. This is
-necessary because assignment can be chained, e.g. \code{a = b = 2}.
-Each \class{Node} in the list will be one of the following classes:
-\class{AssAttr}, \class{AssList}, \class{AssName}, or
-\class{AssTuple}.
-
-Each target assignment node will describe the kind of object being
-assigned to: \class{AssName} for a simple name, e.g. \code{a = 1}.
-\class{AssAttr} for an attribute assigned, e.g. \code{a.x = 1}.
-\class{AssList} and \class{AssTuple} for list and tuple expansion
-respectively, e.g. \code{a, b, c = a_tuple}.
-
-The target assignment nodes also have a \member{flags} attribute that
-indicates whether the node is being used for assignment or in a delete
-statement. The \class{AssName} is also used to represent a delete
-statement, e.g. \class{del x}.
-
-When an expression contains several attribute references, an
-assignment or delete statement will contain only one \class{AssAttr}
-node -- for the final attribute reference. The other attribute
-references will be represented as \class{Getattr} nodes in the
-\member{expr} attribute of the \class{AssAttr} instance.
-
-\subsection{Examples}
-
-This section shows several simple examples of ASTs for Python source
-code. The examples demonstrate how to use the \function{parse()}
-function, what the repr of an AST looks like, and how to access
-attributes of an AST node.
-
-The first module defines a single function. Assume it is stored in
-\file{/tmp/doublelib.py}.
-
-\begin{verbatim}
-"""This is an example module.
-
-This is the docstring.
-"""
-
-def double(x):
- "Return twice the argument"
- return x * 2
-\end{verbatim}
-
-In the interactive interpreter session below, I have reformatted the
-long AST reprs for readability. The AST reprs use unqualified class
-names. If you want to create an instance from a repr, you must import
-the class names from the \module{compiler.ast} module.
-
-\begin{verbatim}
->>> import compiler
->>> mod = compiler.parseFile("/tmp/doublelib.py")
->>> mod
-Module('This is an example module.\n\nThis is the docstring.\n',
- Stmt([Function('double', ['x'], [], 0, 'Return twice the argument',
- Stmt([Return(Mul((Name('x'), Const(2))))]))]))
->>> from compiler.ast import *
->>> Module('This is an example module.\n\nThis is the docstring.\n',
-... Stmt([Function('double', ['x'], [], 0, 'Return twice the argument',
-... Stmt([Return(Mul((Name('x'), Const(2))))]))]))
-Module('This is an example module.\n\nThis is the docstring.\n',
- Stmt([Function('double', ['x'], [], 0, 'Return twice the argument',
- Stmt([Return(Mul((Name('x'), Const(2))))]))]))
->>> mod.doc
-'This is an example module.\n\nThis is the docstring.\n'
->>> for node in mod.node.nodes:
-... print node
-...
-Function('double', ['x'], [], 0, 'Return twice the argument',
- Stmt([Return(Mul((Name('x'), Const(2))))]))
->>> func = mod.node.nodes[0]
->>> func.code
-Stmt([Return(Mul((Name('x'), Const(2))))])
-\end{verbatim}
-
-\section{Using Visitors to Walk ASTs}
-
-\declaremodule{}{compiler.visitor}
-
-The visitor pattern is ... The \refmodule{compiler} package uses a
-variant on the visitor pattern that takes advantage of Python's
-introspection features to elminiate the need for much of the visitor's
-infrastructure.
-
-The classes being visited do not need to be programmed to accept
-visitors. The visitor need only define visit methods for classes it
-is specifically interested in; a default visit method can handle the
-rest.
-
-XXX The magic \method{visit()} method for visitors.
-
-\begin{funcdesc}{walk}{tree, visitor\optional{, verbose}}
-\end{funcdesc}
-
-\begin{classdesc}{ASTVisitor}{}
-
-The \class{ASTVisitor} is responsible for walking over the tree in the
-correct order. A walk begins with a call to \method{preorder()}. For
-each node, it checks the \var{visitor} argument to \method{preorder()}
-for a method named `visitNodeType,' where NodeType is the name of the
-node's class, e.g. for a \class{While} node a \method{visitWhile()}
-would be called. If the method exists, it is called with the node as
-its first argument.
-
-The visitor method for a particular node type can control how child
-nodes are visited during the walk. The \class{ASTVisitor} modifies
-the visitor argument by adding a visit method to the visitor; this
-method can be used to visit a particular child node. If no visitor is
-found for a particular node type, the \method{default()} method is
-called.
-\end{classdesc}
-
-\class{ASTVisitor} objects have the following methods:
-
-XXX describe extra arguments
-
-\begin{methoddesc}{default}{node\optional{, \moreargs}}
-\end{methoddesc}
-
-\begin{methoddesc}{dispatch}{node\optional{, \moreargs}}
-\end{methoddesc}
-
-\begin{methoddesc}{preorder}{tree, visitor}
-\end{methoddesc}
-
-
-\section{Bytecode Generation}
-
-The code generator is a visitor that emits bytecodes. Each visit method
-can call the \method{emit()} method to emit a new bytecode. The basic
-code generator is specialized for modules, classes, and functions. An
-assembler converts that emitted instructions to the low-level bytecode
-format. It handles things like generator of constant lists of code
-objects and calculation of jump offsets.
diff --git a/Doc/lib/distutils.tex b/Doc/lib/distutils.tex
deleted file mode 100644
index f7783e319c..0000000000
--- a/Doc/lib/distutils.tex
+++ /dev/null
@@ -1,37 +0,0 @@
-\section{\module{distutils} ---
- Building and installing Python modules}
-
-\declaremodule{standard}{distutils}
-\modulesynopsis{Support for building and installing Python modules
- into an existing Python installation.}
-\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
-
-
-The \module{distutils} package provides support for building and
-installing additional modules into a Python installation. The new
-modules may be either 100\%{}-pure Python, or may be extension modules
-written in C, or may be collections of Python packages which include
-modules coded in both Python and C.
-
-This package is discussed in two separate documents which are included
-in the Python documentation package. To learn about distributing new
-modules using the \module{distutils} facilities, read
-\citetitle[../dist/dist.html]{Distributing Python Modules}. To learn
-about installing Python modules, whether or not the author made use of
-the \module{distutils} package, read
-\citetitle[../inst/inst.html]{Installing Python Modules}.
-
-
-\begin{seealso}
- \seetitle[../dist/dist.html]{Distributing Python Modules}{The manual
- for developers and packagers of Python modules. This
- describes how to prepare \module{distutils}-based packages
- so that they may be easily installed into an existing
- Python installaion.}
-
- \seetitle[../inst/inst.html]{Installing Python Modules}{An
- ``administrators'' manual which includes information on
- installing modules into an existing Python installation.
- You do not need to be a Python programmer to read this
- manual.}
-\end{seealso}
diff --git a/Doc/lib/email-dir.py b/Doc/lib/email-dir.py
deleted file mode 100644
index aa3b5e5191..0000000000
--- a/Doc/lib/email-dir.py
+++ /dev/null
@@ -1,123 +0,0 @@
-#!/usr/bin/env python
-
-"""Send the contents of a directory as a MIME message.
-
-Usage: dirmail [options] from to [to ...]*
-
-Options:
- -h / --help
- Print this message and exit.
-
- -d directory
- --directory=directory
- Mail the contents of the specified directory, otherwise use the
- current directory. Only the regular files in the directory are sent,
- and we don't recurse to subdirectories.
-
-`from' is the email address of the sender of the message.
-
-`to' is the email address of the recipient of the message, and multiple
-recipients may be given.
-
-The email is sent by forwarding to your local SMTP server, which then does the
-normal delivery process. Your local machine must be running an SMTP server.
-"""
-
-import sys
-import os
-import getopt
-import smtplib
-# For guessing MIME type based on file name extension
-import mimetypes
-
-from email import Encoders
-from email.Message import Message
-from email.MIMEAudio import MIMEAudio
-from email.MIMEMultipart import MIMEMultipart
-from email.MIMEImage import MIMEImage
-from email.MIMEText import MIMEText
-
-COMMASPACE = ', '
-
-
-def usage(code, msg=''):
- print >> sys.stderr, __doc__
- if msg:
- print >> sys.stderr, msg
- sys.exit(code)
-
-
-def main():
- try:
- opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'directory='])
- except getopt.error, msg:
- usage(1, msg)
-
- dir = os.curdir
- for opt, arg in opts:
- if opt in ('-h', '--help'):
- usage(0)
- elif opt in ('-d', '--directory'):
- dir = arg
-
- if len(args) < 2:
- usage(1)
-
- sender = args[0]
- recips = args[1:]
-
- # Create the enclosing (outer) message
- outer = MIMEMultipart()
- outer['Subject'] = 'Contents of directory %s' % os.path.abspath(dir)
- outer['To'] = COMMASPACE.join(recips)
- outer['From'] = sender
- outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
- # To guarantee the message ends with a newline
- outer.epilogue = ''
-
- for filename in os.listdir(dir):
- path = os.path.join(dir, filename)
- if not os.path.isfile(path):
- continue
- # Guess the content type based on the file's extension. Encoding
- # will be ignored, although we should check for simple things like
- # gzip'd or compressed files.
- ctype, encoding = mimetypes.guess_type(path)
- if ctype is None or encoding is not None:
- # No guess could be made, or the file is encoded (compressed), so
- # use a generic bag-of-bits type.
- ctype = 'application/octet-stream'
- maintype, subtype = ctype.split('/', 1)
- if maintype == 'text':
- fp = open(path)
- # Note: we should handle calculating the charset
- msg = MIMEText(fp.read(), _subtype=subtype)
- fp.close()
- elif maintype == 'image':
- fp = open(path, 'rb')
- msg = MIMEImage(fp.read(), _subtype=subtype)
- fp.close()
- elif maintype == 'audio':
- fp = open(path, 'rb')
- msg = MIMEAudio(fp.read(), _subtype=subtype)
- fp.close()
- else:
- fp = open(path, 'rb')
- msg = MIMEBase(maintype, subtype)
- msg.set_payload(fp.read())
- fp.close()
- # Encode the payload using Base64
- Encoders.encode_base64(msg)
- # Set the filename parameter
- msg.add_header('Content-Disposition', 'attachment', filename=filename)
- outer.attach(msg)
-
- # Now send the message
- s = smtplib.SMTP()
- s.connect()
- s.sendmail(sender, recips, outer.as_string())
- s.close()
-
-
-if __name__ == '__main__':
- main()
diff --git a/Doc/lib/email-mime.py b/Doc/lib/email-mime.py
deleted file mode 100644
index 28c8d2ed83..0000000000
--- a/Doc/lib/email-mime.py
+++ /dev/null
@@ -1,34 +0,0 @@
-# Import smtplib for the actual sending function
-import smtplib
-
-# Here are the email pacakge modules we'll need
-from email.MIMEImage import MIMEImage
-from email.MIMEMultipart import MIMEMultipart
-
-COMMASPACE = ', '
-
-# Create the container (outer) email message.
-msg = MIMEMultipart()
-msg['Subject'] = 'Our family reunion'
-# me == the sender's email address
-# family = the list of all recipients' email addresses
-msg['From'] = me
-msg['To'] = COMMASPACE.join(family)
-msg.preamble = 'Our family reunion'
-# Guarantees the message ends in a newline
-msg.epilogue = ''
-
-# Assume we know that the image files are all in PNG format
-for file in pngfiles:
- # Open the files in binary mode. Let the MIMEImage class automatically
- # guess the specific image type.
- fp = open(file, 'rb')
- img = MIMEImage(fp.read())
- fp.close()
- msg.attach(img)
-
-# Send the email via our own SMTP server.
-s = smtplib.SMTP()
-s.connect()
-s.sendmail(me, family, msg.as_string())
-s.close()
diff --git a/Doc/lib/email-simple.py b/Doc/lib/email-simple.py
deleted file mode 100644
index a445f1bd1d..0000000000
--- a/Doc/lib/email-simple.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# Import smtplib for the actual sending function
-import smtplib
-
-# Import the email modules we'll need
-from email.MIMEText import MIMEText
-
-# Open a plain text file for reading. For this example, assume that
-# the text file contains only ASCII characters.
-fp = open(textfile, 'rb')
-# Create a text/plain message
-msg = MIMEText(fp.read())
-fp.close()
-
-# me == the sender's email address
-# you == the recipient's email address
-msg['Subject'] = 'The contents of %s' % textfile
-msg['From'] = me
-msg['To'] = you
-
-# Send the message via our own SMTP server, but don't include the
-# envelope header.
-s = smtplib.SMTP()
-s.connect()
-s.sendmail(me, [you], msg.as_string())
-s.close()
diff --git a/Doc/lib/email-unpack.py b/Doc/lib/email-unpack.py
deleted file mode 100644
index b166fdba7d..0000000000
--- a/Doc/lib/email-unpack.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/env python
-
-"""Unpack a MIME message into a directory of files.
-
-Usage: unpackmail [options] msgfile
-
-Options:
- -h / --help
- Print this message and exit.
-
- -d directory
- --directory=directory
- Unpack the MIME message into the named directory, which will be
- created if it doesn't already exist.
-
-msgfile is the path to the file containing the MIME message.
-"""
-
-import sys
-import os
-import getopt
-import errno
-import mimetypes
-import email
-
-
-def usage(code, msg=''):
- print >> sys.stderr, __doc__
- if msg:
- print >> sys.stderr, msg
- sys.exit(code)
-
-
-def main():
- try:
- opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'directory='])
- except getopt.error, msg:
- usage(1, msg)
-
- dir = os.curdir
- for opt, arg in opts:
- if opt in ('-h', '--help'):
- usage(0)
- elif opt in ('-d', '--directory'):
- dir = arg
-
- try:
- msgfile = args[0]
- except IndexError:
- usage(1)
-
- try:
- os.mkdir(dir)
- except OSError, e:
- # Ignore directory exists error
- if e.errno <> errno.EEXIST: raise
-
- fp = open(msgfile)
- msg = email.message_from_file(fp)
- fp.close()
-
- counter = 1
- for part in msg.walk():
- # multipart/* are just containers
- if part.get_content_maintype() == 'multipart':
- continue
- # Applications should really sanitize the given filename so that an
- # email message can't be used to overwrite important files
- filename = part.get_filename()
- if not filename:
- ext = mimetypes.guess_extension(part.get_type())
- if not ext:
- # Use a generic bag-of-bits extension
- ext = '.bin'
- filename = 'part-%03d%s' % (counter, ext)
- counter += 1
- fp = open(os.path.join(dir, filename), 'wb')
- fp.write(part.get_payload(decode=1))
- fp.close()
-
-
-if __name__ == '__main__':
- main()
diff --git a/Doc/lib/email.tex b/Doc/lib/email.tex
deleted file mode 100644
index debed70a70..0000000000
--- a/Doc/lib/email.tex
+++ /dev/null
@@ -1,336 +0,0 @@
-% Copyright (C) 2001,2002 Python Software Foundation
-% Author: barry@zope.com (Barry Warsaw)
-
-\section{\module{email} ---
- An email and MIME handling package}
-
-\declaremodule{standard}{email}
-\modulesynopsis{Package supporting the parsing, manipulating, and
- generating email messages, including MIME documents.}
-\moduleauthor{Barry A. Warsaw}{barry@zope.com}
-\sectionauthor{Barry A. Warsaw}{barry@zope.com}
-
-\versionadded{2.2}
-
-The \module{email} package is a library for managing email messages,
-including MIME and other \rfc{2822}-based message documents. It
-subsumes most of the functionality in several older standard modules
-such as \refmodule{rfc822}, \refmodule{mimetools},
-\refmodule{multifile}, and other non-standard packages such as
-\module{mimecntl}. It is specifically \emph{not} designed to do any
-sending of email messages to SMTP (\rfc{2821}) servers; that is the
-function of the \refmodule{smtplib} module. The \module{email}
-package attempts to be as RFC-compliant as possible, supporting in
-addition to \rfc{2822}, such MIME-related RFCs as
-\rfc{2045}-\rfc{2047}, and \rfc{2231}.
-
-The primary distinguishing feature of the \module{email} package is
-that it splits the parsing and generating of email messages from the
-internal \emph{object model} representation of email. Applications
-using the \module{email} package deal primarily with objects; you can
-add sub-objects to messages, remove sub-objects from messages,
-completely re-arrange the contents, etc. There is a separate parser
-and a separate generator which handles the transformation from flat
-text to the object model, and then back to flat text again. There
-are also handy subclasses for some common MIME object types, and a few
-miscellaneous utilities that help with such common tasks as extracting
-and parsing message field values, creating RFC-compliant dates, etc.
-
-The following sections describe the functionality of the
-\module{email} package. The ordering follows a progression that
-should be common in applications: an email message is read as flat
-text from a file or other source, the text is parsed to produce the
-object structure of the email message, this structure is manipulated,
-and finally rendered back into flat text.
-
-It is perfectly feasible to create the object structure out of whole
-cloth --- i.e. completely from scratch. From there, a similar
-progression can be taken as above.
-
-Also included are detailed specifications of all the classes and
-modules that the \module{email} package provides, the exception
-classes you might encounter while using the \module{email} package,
-some auxiliary utilities, and a few examples. For users of the older
-\module{mimelib} package, or previous versions of the \module{email}
-package, a section on differences and porting is provided.
-
-\begin{seealso}
- \seemodule{smtplib}{SMTP protocol client}
-\end{seealso}
-
-\subsection{Representing an email message}
-\input{emailmessage}
-
-\subsection{Parsing email messages}
-\input{emailparser}
-
-\subsection{Generating MIME documents}
-\input{emailgenerator}
-
-\subsection{Creating email and MIME objects from scratch}
-\input{emailmimebase}
-
-\subsection{Internationalized headers}
-\input{emailheaders}
-
-\subsection{Representing character sets}
-\input{emailcharsets}
-
-\subsection{Encoders}
-\input{emailencoders}
-
-\subsection{Exception classes}
-\input{emailexc}
-
-\subsection{Miscellaneous utilities}
-\input{emailutil}
-
-\subsection{Iterators}
-\input{emailiter}
-
-\subsection{Differences from \module{email} v1 (up to Python 2.2.1)}
-
-Version 1 of the \module{email} package was bundled with Python
-releases up to Python 2.2.1. Version 2 was developed for the Python
-2.3 release, and backported to Python 2.2.2. It was also available as
-a separate distutils based package. \module{email} version 2 is
-almost entirely backward compatible with version 1, with the
-following differences:
-
-\begin{itemize}
-\item The \module{email.Header} and \module{email.Charset} modules
- have been added.
-
-\item The pickle format for \class{Message} instances has changed.
- Since this was never (and still isn't) formally defined, this
- isn't considered a backward incompatibility. However if your
- application pickles and unpickles \class{Message} instances, be
- aware that in \module{email} version 2, \class{Message}
- instances now have private variables \var{_charset} and
- \var{_default_type}.
-
-\item Several methods in the \class{Message} class have been
- deprecated, or their signatures changed. Also, many new methods
- have been added. See the documentation for the \class{Message}
- class for details. The changes should be completely backward
- compatible.
-
-\item The object structure has changed in the face of
- \mimetype{message/rfc822} content types. In \module{email}
- version 1, such a type would be represented by a scalar payload,
- i.e. the container message's \method{is_multipart()} returned
- false, \method{get_payload()} was not a list object, but a single
- \class{Message} instance.
-
- This structure was inconsistent with the rest of the package, so
- the object representation for \mimetype{message/rfc822} content
- types was changed. In \module{email} version 2, the container
- \emph{does} return \code{True} from \method{is_multipart()}, and
- \method{get_payload()} returns a list containing a single
- \class{Message} item.
-
- Note that this is one place that backward compatibility could
- not be completely maintained. However, if you're already
- testing the return type of \method{get_payload()}, you should be
- fine. You just need to make sure your code doesn't do a
- \method{set_payload()} with a \class{Message} instance on a
- container with a content type of \mimetype{message/rfc822}.
-
-\item The \class{Parser} constructor's \var{strict} argument was
- added, and its \method{parse()} and \method{parsestr()} methods
- grew a \var{headersonly} argument. The \var{strict} flag was
- also added to functions \function{email.message_from_file()}
- and \function{email.message_from_string()}.
-
-\item \method{Generator.__call__()} is deprecated; use
- \method{Generator.flatten()} instead. The \class{Generator}
- class has also grown the \method{clone()} method.
-
-\item The \class{DecodedGenerator} class in the
- \module{email.Generator} module was added.
-
-\item The intermediate base classes \class{MIMENonMultipart} and
- \class{MIMEMultipart} have been added, and interposed in the
- class hierarchy for most of the other MIME-related derived
- classes.
-
-\item The \var{_encoder} argument to the \class{MIMEText} constructor
- has been deprecated. Encoding now happens implicitly based
- on the \var{_charset} argument.
-
-\item The following functions in the \module{email.Utils} module have
- been deprecated: \function{dump_address_pairs()},
- \function{decode()}, and \function{encode()}. The following
- functions have been added to the module:
- \function{make_msgid()}, \function{decode_rfc2231()},
- \function{encode_rfc2231()}, and \function{decode_params()}.
-
-\item The non-public function \function{email.Iterators._structure()}
- was added.
-\end{itemize}
-
-\subsection{Differences from \module{mimelib}}
-
-The \module{email} package was originally prototyped as a separate
-library called
-\ulink{\module{mimelib}}{http://mimelib.sf.net/}.
-Changes have been made so that
-method names are more consistent, and some methods or modules have
-either been added or removed. The semantics of some of the methods
-have also changed. For the most part, any functionality available in
-\module{mimelib} is still available in the \refmodule{email} package,
-albeit often in a different way. Backward compatibility between
-the \module{mimelib} package and the \module{email} package was not a
-priority.
-
-Here is a brief description of the differences between the
-\module{mimelib} and the \refmodule{email} packages, along with hints on
-how to port your applications.
-
-Of course, the most visible difference between the two packages is
-that the package name has been changed to \refmodule{email}. In
-addition, the top-level package has the following differences:
-
-\begin{itemize}
-\item \function{messageFromString()} has been renamed to
- \function{message_from_string()}.
-
-\item \function{messageFromFile()} has been renamed to
- \function{message_from_file()}.
-
-\end{itemize}
-
-The \class{Message} class has the following differences:
-
-\begin{itemize}
-\item The method \method{asString()} was renamed to \method{as_string()}.
-
-\item The method \method{ismultipart()} was renamed to
- \method{is_multipart()}.
-
-\item The \method{get_payload()} method has grown a \var{decode}
- optional argument.
-
-\item The method \method{getall()} was renamed to \method{get_all()}.
-
-\item The method \method{addheader()} was renamed to \method{add_header()}.
-
-\item The method \method{gettype()} was renamed to \method{get_type()}.
-
-\item The method\method{getmaintype()} was renamed to
- \method{get_main_type()}.
-
-\item The method \method{getsubtype()} was renamed to
- \method{get_subtype()}.
-
-\item The method \method{getparams()} was renamed to
- \method{get_params()}.
- Also, whereas \method{getparams()} returned a list of strings,
- \method{get_params()} returns a list of 2-tuples, effectively
- the key/value pairs of the parameters, split on the \character{=}
- sign.
-
-\item The method \method{getparam()} was renamed to \method{get_param()}.
-
-\item The method \method{getcharsets()} was renamed to
- \method{get_charsets()}.
-
-\item The method \method{getfilename()} was renamed to
- \method{get_filename()}.
-
-\item The method \method{getboundary()} was renamed to
- \method{get_boundary()}.
-
-\item The method \method{setboundary()} was renamed to
- \method{set_boundary()}.
-
-\item The method \method{getdecodedpayload()} was removed. To get
- similar functionality, pass the value 1 to the \var{decode} flag
- of the {get_payload()} method.
-
-\item The method \method{getpayloadastext()} was removed. Similar
- functionality
- is supported by the \class{DecodedGenerator} class in the
- \refmodule{email.Generator} module.
-
-\item The method \method{getbodyastext()} was removed. You can get
- similar functionality by creating an iterator with
- \function{typed_subpart_iterator()} in the
- \refmodule{email.Iterators} module.
-\end{itemize}
-
-The \class{Parser} class has no differences in its public interface.
-It does have some additional smarts to recognize
-\mimetype{message/delivery-status} type messages, which it represents as
-a \class{Message} instance containing separate \class{Message}
-subparts for each header block in the delivery status
-notification\footnote{Delivery Status Notifications (DSN) are defined
-in \rfc{1894}.}.
-
-The \class{Generator} class has no differences in its public
-interface. There is a new class in the \refmodule{email.Generator}
-module though, called \class{DecodedGenerator} which provides most of
-the functionality previously available in the
-\method{Message.getpayloadastext()} method.
-
-The following modules and classes have been changed:
-
-\begin{itemize}
-\item The \class{MIMEBase} class constructor arguments \var{_major}
- and \var{_minor} have changed to \var{_maintype} and
- \var{_subtype} respectively.
-
-\item The \code{Image} class/module has been renamed to
- \code{MIMEImage}. The \var{_minor} argument has been renamed to
- \var{_subtype}.
-
-\item The \code{Text} class/module has been renamed to
- \code{MIMEText}. The \var{_minor} argument has been renamed to
- \var{_subtype}.
-
-\item The \code{MessageRFC822} class/module has been renamed to
- \code{MIMEMessage}. Note that an earlier version of
- \module{mimelib} called this class/module \code{RFC822}, but
- that clashed with the Python standard library module
- \refmodule{rfc822} on some case-insensitive file systems.
-
- Also, the \class{MIMEMessage} class now represents any kind of
- MIME message with main type \mimetype{message}. It takes an
- optional argument \var{_subtype} which is used to set the MIME
- subtype. \var{_subtype} defaults to \mimetype{rfc822}.
-\end{itemize}
-
-\module{mimelib} provided some utility functions in its
-\module{address} and \module{date} modules. All of these functions
-have been moved to the \refmodule{email.Utils} module.
-
-The \code{MsgReader} class/module has been removed. Its functionality
-is most closely supported in the \function{body_line_iterator()}
-function in the \refmodule{email.Iterators} module.
-
-\subsection{Examples}
-
-Here are a few examples of how to use the \module{email} package to
-read, write, and send simple email messages, as well as more complex
-MIME messages.
-
-First, let's see how to create and send a simple text message:
-
-\verbatiminput{email-simple.py}
-
-Here's an example of how to send a MIME message containing a bunch of
-family pictures that may be residing in a directory:
-
-\verbatiminput{email-mime.py}
-
-Here's an example of how to send the entire contents of a directory as
-an email message:
-\footnote{Thanks to Matthew Dixon Cowles for the original inspiration
- and examples.}
-
-\verbatiminput{email-dir.py}
-
-And finally, here's an example of how to unpack a MIME message like
-the one above, into a directory of files:
-
-\verbatiminput{email-unpack.py}
diff --git a/Doc/lib/emailcharsets.tex b/Doc/lib/emailcharsets.tex
deleted file mode 100644
index 18f2a016c0..0000000000
--- a/Doc/lib/emailcharsets.tex
+++ /dev/null
@@ -1,242 +0,0 @@
-\declaremodule{standard}{email.Charset}
-\modulesynopsis{Character Sets}
-
-This module provides a class \class{Charset} for representing
-character sets and character set conversions in email messages, as
-well as a character set registry and several convenience methods for
-manipulating this registry. Instances of \class{Charset} are used in
-several other modules within the \module{email} package.
-
-\versionadded{2.2.2}
-
-\begin{classdesc}{Charset}{\optional{input_charset}}
-Map character sets to their email properties.
-
-This class provides information about the requirements imposed on
-email for a specific character set. It also provides convenience
-routines for converting between character sets, given the availability
-of the applicable codecs. Given a character set, it will do its best
-to provide information on how to use that character set in an email
-message in an RFC-compliant way.
-
-Certain character sets must be encoded with quoted-printable or base64
-when used in email headers or bodies. Certain character sets must be
-converted outright, and are not allowed in email.
-
-Optional \var{input_charset} is as described below; it is always
-coerced to lower case. After being alias normalized it is also used
-as a lookup into the registry of character sets to find out the header
-encoding, body encoding, and output conversion codec to be used for
-the character set. For example, if
-\var{input_charset} is \code{iso-8859-1}, then headers and bodies will
-be encoded using quoted-printable and no output conversion codec is
-necessary. If \var{input_charset} is \code{euc-jp}, then headers will
-be encoded with base64, bodies will not be encoded, but output text
-will be converted from the \code{euc-jp} character set to the
-\code{iso-2022-jp} character set.
-\end{classdesc}
-
-\class{Charset} instances have the following data attributes:
-
-\begin{datadesc}{input_charset}
-The initial character set specified. Common aliases are converted to
-their \emph{official} email names (e.g. \code{latin_1} is converted to
-\code{iso-8859-1}). Defaults to 7-bit \code{us-ascii}.
-\end{datadesc}
-
-\begin{datadesc}{header_encoding}
-If the character set must be encoded before it can be used in an
-email header, this attribute will be set to \code{Charset.QP} (for
-quoted-printable), \code{Charset.BASE64} (for base64 encoding), or
-\code{Charset.SHORTEST} for the shortest of QP or BASE64 encoding.
-Otherwise, it will be \code{None}.
-\end{datadesc}
-
-\begin{datadesc}{body_encoding}
-Same as \var{header_encoding}, but describes the encoding for the
-mail message's body, which indeed may be different than the header
-encoding. \code{Charset.SHORTEST} is not allowed for
-\var{body_encoding}.
-\end{datadesc}
-
-\begin{datadesc}{output_charset}
-Some character sets must be converted before they can be used in
-email headers or bodies. If the \var{input_charset} is one of
-them, this attribute will contain the name of the character set
-output will be converted to. Otherwise, it will be \code{None}.
-\end{datadesc}
-
-\begin{datadesc}{input_codec}
-The name of the Python codec used to convert the \var{input_charset} to
-Unicode. If no conversion codec is necessary, this attribute will be
-\code{None}.
-\end{datadesc}
-
-\begin{datadesc}{output_codec}
-The name of the Python codec used to convert Unicode to the
-\var{output_charset}. If no conversion codec is necessary, this
-attribute will have the same value as the \var{input_codec}.
-\end{datadesc}
-
-\class{Charset} instances also have the following methods:
-
-\begin{methoddesc}[Charset]{get_body_encoding}{}
-Return the content transfer encoding used for body encoding.
-
-This is either the string \samp{quoted-printable} or \samp{base64}
-depending on the encoding used, or it is a function, in which case you
-should call the function with a single argument, the Message object
-being encoded. The function should then set the
-\mailheader{Content-Transfer-Encoding} header itself to whatever is
-appropriate.
-
-Returns the string \samp{quoted-printable} if
-\var{body_encoding} is \code{QP}, returns the string
-\samp{base64} if \var{body_encoding} is \code{BASE64}, and returns the
-string \samp{7bit} otherwise.
-\end{methoddesc}
-
-\begin{methoddesc}{convert}{s}
-Convert the string \var{s} from the \var{input_codec} to the
-\var{output_codec}.
-\end{methoddesc}
-
-\begin{methoddesc}{to_splittable}{s}
-Convert a possibly multibyte string to a safely splittable format.
-\var{s} is the string to split.
-
-Uses the \var{input_codec} to try and convert the string to Unicode,
-so it can be safely split on character boundaries (even for multibyte
-characters).
-
-Returns the string as-is if it isn't known how to convert \var{s} to
-Unicode with the \var{input_charset}.
-
-Characters that could not be converted to Unicode will be replaced
-with the Unicode replacement character \character{U+FFFD}.
-\end{methoddesc}
-
-\begin{methoddesc}{from_splittable}{ustr\optional{, to_output}}
-Convert a splittable string back into an encoded string. \var{ustr}
-is a Unicode string to ``unsplit''.
-
-This method uses the proper codec to try and convert the string from
-Unicode back into an encoded format. Return the string as-is if it is
-not Unicode, or if it could not be converted from Unicode.
-
-Characters that could not be converted from Unicode will be replaced
-with an appropriate character (usually \character{?}).
-
-If \var{to_output} is \code{True} (the default), uses
-\var{output_codec} to convert to an
-encoded format. If \var{to_output} is \code{False}, it uses
-\var{input_codec}.
-\end{methoddesc}
-
-\begin{methoddesc}{get_output_charset}{}
-Return the output character set.
-
-This is the \var{output_charset} attribute if that is not \code{None},
-otherwise it is \var{input_charset}.
-\end{methoddesc}
-
-\begin{methoddesc}{encoded_header_len}{}
-Return the length of the encoded header string, properly calculating
-for quoted-printable or base64 encoding.
-\end{methoddesc}
-
-\begin{methoddesc}{header_encode}{s\optional{, convert}}
-Header-encode the string \var{s}.
-
-If \var{convert} is \code{True}, the string will be converted from the
-input charset to the output charset automatically. This is not useful
-for multibyte character sets, which have line length issues (multibyte
-characters must be split on a character, not a byte boundary); use the
-higher-level \class{Header} class to deal with these issues (see
-\refmodule{email.Header}). \var{convert} defaults to \code{False}.
-
-The type of encoding (base64 or quoted-printable) will be based on
-the \var{header_encoding} attribute.
-\end{methoddesc}
-
-\begin{methoddesc}{body_encode}{s\optional{, convert}}
-Body-encode the string \var{s}.
-
-If \var{convert} is \code{True} (the default), the string will be
-converted from the input charset to output charset automatically.
-Unlike \method{header_encode()}, there are no issues with byte
-boundaries and multibyte charsets in email bodies, so this is usually
-pretty safe.
-
-The type of encoding (base64 or quoted-printable) will be based on
-the \var{body_encoding} attribute.
-\end{methoddesc}
-
-The \class{Charset} class also provides a number of methods to support
-standard operations and built-in functions.
-
-\begin{methoddesc}[Charset]{__str__}{}
-Returns \var{input_charset} as a string coerced to lower case.
-\method{__repr__()} is an alias for \method{__str__()}.
-\end{methoddesc}
-
-\begin{methoddesc}[Charset]{__eq__}{other}
-This method allows you to compare two \class{Charset} instances for equality.
-\end{methoddesc}
-
-\begin{methoddesc}[Header]{__ne__}{other}
-This method allows you to compare two \class{Charset} instances for inequality.
-\end{methoddesc}
-
-The \module{email.Charset} module also provides the following
-functions for adding new entries to the global character set, alias,
-and codec registries:
-
-\begin{funcdesc}{add_charset}{charset\optional{, header_enc\optional{,
- body_enc\optional{, output_charset}}}}
-Add character properties to the global registry.
-
-\var{charset} is the input character set, and must be the canonical
-name of a character set.
-
-Optional \var{header_enc} and \var{body_enc} is either
-\code{Charset.QP} for quoted-printable, \code{Charset.BASE64} for
-base64 encoding, \code{Charset.SHORTEST} for the shortest of
-quoted-printable or base64 encoding, or \code{None} for no encoding.
-\code{SHORTEST} is only valid for \var{header_enc}. The default is
-\code{None} for no encoding.
-
-Optional \var{output_charset} is the character set that the output
-should be in. Conversions will proceed from input charset, to
-Unicode, to the output charset when the method
-\method{Charset.convert()} is called. The default is to output in the
-same character set as the input.
-
-Both \var{input_charset} and \var{output_charset} must have Unicode
-codec entries in the module's character set-to-codec mapping; use
-\function{add_codec()} to add codecs the module does
-not know about. See the \refmodule{codecs} module's documentation for
-more information.
-
-The global character set registry is kept in the module global
-dictionary \code{CHARSETS}.
-\end{funcdesc}
-
-\begin{funcdesc}{add_alias}{alias, canonical}
-Add a character set alias. \var{alias} is the alias name,
-e.g. \code{latin-1}. \var{canonical} is the character set's canonical
-name, e.g. \code{iso-8859-1}.
-
-The global charset alias registry is kept in the module global
-dictionary \code{ALIASES}.
-\end{funcdesc}
-
-\begin{funcdesc}{add_codec}{charset, codecname}
-Add a codec that map characters in the given character set to and from
-Unicode.
-
-\var{charset} is the canonical name of a character set.
-\var{codecname} is the name of a Python codec, as appropriate for the
-second argument to the \function{unicode()} built-in, or to the
-\method{encode()} method of a Unicode string.
-\end{funcdesc}
diff --git a/Doc/lib/emailencoders.tex b/Doc/lib/emailencoders.tex
deleted file mode 100644
index cd54d68be9..0000000000
--- a/Doc/lib/emailencoders.tex
+++ /dev/null
@@ -1,47 +0,0 @@
-\declaremodule{standard}{email.Encoders}
-\modulesynopsis{Encoders for email message payloads.}
-
-When creating \class{Message} objects from scratch, you often need to
-encode the payloads for transport through compliant mail servers.
-This is especially true for \mimetype{image/*} and \mimetype{text/*}
-type messages containing binary data.
-
-The \module{email} package provides some convenient encodings in its
-\module{Encoders} module. These encoders are actually used by the
-\class{MIMEImage} and \class{MIMEText} class constructors to provide default
-encodings. All encoder functions take exactly one argument, the
-message object to encode. They usually extract the payload, encode
-it, and reset the payload to this newly encoded value. They should also
-set the \mailheader{Content-Transfer-Encoding} header as appropriate.
-
-Here are the encoding functions provided:
-
-\begin{funcdesc}{encode_quopri}{msg}
-Encodes the payload into quoted-printable form and sets the
-\mailheader{Content-Transfer-Encoding} header to
-\code{quoted-printable}\footnote{Note that encoding with
-\method{encode_quopri()} also encodes all tabs and space characters in
-the data.}.
-This is a good encoding to use when most of your payload is normal
-printable data, but contains a few unprintable characters.
-\end{funcdesc}
-
-\begin{funcdesc}{encode_base64}{msg}
-Encodes the payload into base64 form and sets the
-\mailheader{Content-Transfer-Encoding} header to
-\code{base64}. This is a good encoding to use when most of your payload
-is unprintable data since it is a more compact form than
-quoted-printable. The drawback of base64 encoding is that it
-renders the text non-human readable.
-\end{funcdesc}
-
-\begin{funcdesc}{encode_7or8bit}{msg}
-This doesn't actually modify the message's payload, but it does set
-the \mailheader{Content-Transfer-Encoding} header to either \code{7bit} or
-\code{8bit} as appropriate, based on the payload data.
-\end{funcdesc}
-
-\begin{funcdesc}{encode_noop}{msg}
-This does nothing; it doesn't even set the
-\mailheader{Content-Transfer-Encoding} header.
-\end{funcdesc}
diff --git a/Doc/lib/emailexc.tex b/Doc/lib/emailexc.tex
deleted file mode 100644
index 824a276f17..0000000000
--- a/Doc/lib/emailexc.tex
+++ /dev/null
@@ -1,54 +0,0 @@
-\declaremodule{standard}{email.Errors}
-\modulesynopsis{The exception classes used by the email package.}
-
-The following exception classes are defined in the
-\module{email.Errors} module:
-
-\begin{excclassdesc}{MessageError}{}
-This is the base class for all exceptions that the \module{email}
-package can raise. It is derived from the standard
-\exception{Exception} class and defines no additional methods.
-\end{excclassdesc}
-
-\begin{excclassdesc}{MessageParseError}{}
-This is the base class for exceptions thrown by the \class{Parser}
-class. It is derived from \exception{MessageError}.
-\end{excclassdesc}
-
-\begin{excclassdesc}{HeaderParseError}{}
-Raised under some error conditions when parsing the \rfc{2822} headers of
-a message, this class is derived from \exception{MessageParseError}.
-It can be raised from the \method{Parser.parse()} or
-\method{Parser.parsestr()} methods.
-
-Situations where it can be raised include finding an envelope
-header after the first \rfc{2822} header of the message, finding a
-continuation line before the first \rfc{2822} header is found, or finding
-a line in the headers which is neither a header or a continuation
-line.
-\end{excclassdesc}
-
-\begin{excclassdesc}{BoundaryError}{}
-Raised under some error conditions when parsing the \rfc{2822} headers of
-a message, this class is derived from \exception{MessageParseError}.
-It can be raised from the \method{Parser.parse()} or
-\method{Parser.parsestr()} methods.
-
-Situations where it can be raised include not being able to find the
-starting or terminating boundary in a \mimetype{multipart/*} message
-when strict parsing is used.
-\end{excclassdesc}
-
-\begin{excclassdesc}{MultipartConversionError}{}
-Raised when a payload is added to a \class{Message} object using
-\method{add_payload()}, but the payload is already a scalar and the
-message's \mailheader{Content-Type} main type is not either
-\mimetype{multipart} or missing. \exception{MultipartConversionError}
-multiply inherits from \exception{MessageError} and the built-in
-\exception{TypeError}.
-
-Since \method{Message.add_payload()} is deprecated, this exception is
-rarely raised in practice. However the exception may also be raised
-if the \method{attach()} method is called on an instance of a class
-derived from \class{MIMENonMultipart} (e.g. \class{MIMEImage}).
-\end{excclassdesc}
diff --git a/Doc/lib/emailgenerator.tex b/Doc/lib/emailgenerator.tex
deleted file mode 100644
index 96eb2687a9..0000000000
--- a/Doc/lib/emailgenerator.tex
+++ /dev/null
@@ -1,141 +0,0 @@
-\declaremodule{standard}{email.Generator}
-\modulesynopsis{Generate flat text email messages from a message structure.}
-
-One of the most common tasks is to generate the flat text of the email
-message represented by a message object structure. You will need to do
-this if you want to send your message via the \refmodule{smtplib}
-module or the \refmodule{nntplib} module, or print the message on the
-console. Taking a message object structure and producing a flat text
-document is the job of the \class{Generator} class.
-
-Again, as with the \refmodule{email.Parser} module, you aren't limited
-to the functionality of the bundled generator; you could write one
-from scratch yourself. However the bundled generator knows how to
-generate most email in a standards-compliant way, should handle MIME
-and non-MIME email messages just fine, and is designed so that the
-transformation from flat text, to a message structure via the
-\class{Parser} class, and back to flat text, is idempotent (the input
-is identical to the output).
-
-Here are the public methods of the \class{Generator} class:
-
-\begin{classdesc}{Generator}{outfp\optional{, mangle_from_\optional{,
- maxheaderlen}}}
-The constructor for the \class{Generator} class takes a file-like
-object called \var{outfp} for an argument. \var{outfp} must support
-the \method{write()} method and be usable as the output file in a
-Python extended print statement.
-
-Optional \var{mangle_from_} is a flag that, when \code{True}, puts a
-\samp{>} character in front of any line in the body that starts exactly as
-\samp{From }, i.e. \code{From} followed by a space at the beginning of the
-line. This is the only guaranteed portable way to avoid having such
-lines be mistaken for a Unix mailbox format envelope header separator (see
-\ulink{WHY THE CONTENT-LENGTH FORMAT IS BAD}
-{http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html}
-for details). \var{mangle_from_} defaults to \code{True}, but you
-might want to set this to \code{False} if you are not writing Unix
-mailbox format files.
-
-Optional \var{maxheaderlen} specifies the longest length for a
-non-continued header. When a header line is longer than
-\var{maxheaderlen} (in characters, with tabs expanded to 8 spaces),
-the header will be broken on semicolons and continued as per
-\rfc{2822}. If no semicolon is found, then the header is left alone.
-Set to zero to disable wrapping headers. Default is 78, as
-recommended (but not required) by \rfc{2822}.
-\end{classdesc}
-
-The other public \class{Generator} methods are:
-
-\begin{methoddesc}[Generator]{flatten}{msg\optional{, unixfrom}}
-Print the textual representation of the message object structure rooted at
-\var{msg} to the output file specified when the \class{Generator}
-instance was created. Subparts are visited depth-first and the
-resulting text will be properly MIME encoded.
-
-Optional \var{unixfrom} is a flag that forces the printing of the
-envelope header delimiter before the first \rfc{2822} header of the
-root message object. If the root object has no envelope header, a
-standard one is crafted. By default, this is set to \code{False} to
-inhibit the printing of the envelope delimiter.
-
-Note that for subparts, no envelope header is ever printed.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Generator]{clone}{fp}
-Return an independent clone of this \class{Generator} instance with
-the exact same options.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Generator]{write}{s}
-Write the string \var{s} to the underlying file object,
-i.e. \var{outfp} passed to \class{Generator}'s constructor. This
-provides just enough file-like API for \class{Generator} instances to
-be used in extended print statements.
-\end{methoddesc}
-
-As a convenience, see the methods \method{Message.as_string()} and
-\code{str(aMessage)}, a.k.a. \method{Message.__str__()}, which
-simplify the generation of a formatted string representation of a
-message object. For more detail, see \refmodule{email.Message}.
-
-The \module{email.Generator} module also provides a derived class,
-called \class{DecodedGenerator} which is like the \class{Generator}
-base class, except that non-\mimetype{text} parts are substituted with
-a format string representing the part.
-
-\begin{classdesc}{DecodedGenerator}{outfp\optional{, mangle_from_\optional{,
- maxheaderlen\optional{, fmt}}}}
-
-This class, derived from \class{Generator} walks through all the
-subparts of a message. If the subpart is of main type
-\mimetype{text}, then it prints the decoded payload of the subpart.
-Optional \var{_mangle_from_} and \var{maxheaderlen} are as with the
-\class{Generator} base class.
-
-If the subpart is not of main type \mimetype{text}, optional \var{fmt}
-is a format string that is used instead of the message payload.
-\var{fmt} is expanded with the following keywords, \samp{\%(keyword)s}
-format:
-
-\begin{itemize}
-\item \code{type} -- Full MIME type of the non-\mimetype{text} part
-
-\item \code{maintype} -- Main MIME type of the non-\mimetype{text} part
-
-\item \code{subtype} -- Sub-MIME type of the non-\mimetype{text} part
-
-\item \code{filename} -- Filename of the non-\mimetype{text} part
-
-\item \code{description} -- Description associated with the
- non-\mimetype{text} part
-
-\item \code{encoding} -- Content transfer encoding of the
- non-\mimetype{text} part
-
-\end{itemize}
-
-The default value for \var{fmt} is \code{None}, meaning
-
-\begin{verbatim}
-[Non-text (%(type)s) part of message omitted, filename %(filename)s]
-\end{verbatim}
-
-\versionadded{2.2.2}
-\end{classdesc}
-
-\subsubsection{Deprecated methods}
-
-The following methods are deprecated in \module{email} version 2.
-They are documented here for completeness.
-
-\begin{methoddesc}[Generator]{__call__}{msg\optional{, unixfrom}}
-This method is identical to the \method{flatten()} method.
-
-\deprecated{2.2.2}{Use the \method{flatten()} method instead.}
-\end{methoddesc}
diff --git a/Doc/lib/emailheaders.tex b/Doc/lib/emailheaders.tex
deleted file mode 100644
index d4bbeb8584..0000000000
--- a/Doc/lib/emailheaders.tex
+++ /dev/null
@@ -1,177 +0,0 @@
-\declaremodule{standard}{email.Header}
-\modulesynopsis{Representing non-ASCII headers}
-
-\rfc{2822} is the base standard that describes the format of email
-messages. It derives from the older \rfc{822} standard which came
-into widespread use at a time when most email was composed of \ASCII{}
-characters only. \rfc{2822} is a specification written assuming email
-contains only 7-bit \ASCII{} characters.
-
-Of course, as email has been deployed worldwide, it has become
-internationalized, such that language specific character sets can now
-be used in email messages. The base standard still requires email
-messages to be transfered using only 7-bit \ASCII{} characters, so a
-slew of RFCs have been written describing how to encode email
-containing non-\ASCII{} characters into \rfc{2822}-compliant format.
-These RFCs include \rfc{2045}, \rfc{2046}, \rfc{2047}, and \rfc{2231}.
-The \module{email} package supports these standards in its
-\module{email.Header} and \module{email.Charset} modules.
-
-If you want to include non-\ASCII{} characters in your email headers,
-say in the \mailheader{Subject} or \mailheader{To} fields, you should
-use the \class{Header} class and assign the field in the
-\class{Message} object to an instance of \class{Header} instead of
-using a string for the header value. For example:
-
-\begin{verbatim}
->>> from email.Message import Message
->>> from email.Header import Header
->>> msg = Message()
->>> h = Header('p\xf6stal', 'iso-8859-1')
->>> msg['Subject'] = h
->>> print msg.as_string()
-Subject: =?iso-8859-1?q?p=F6stal?=
-
-
-\end{verbatim}
-
-Notice here how we wanted the \mailheader{Subject} field to contain a
-non-\ASCII{} character? We did this by creating a \class{Header}
-instance and passing in the character set that the byte string was
-encoded in. When the subsequent \class{Message} instance was
-flattened, the \mailheader{Subject} field was properly \rfc{2047}
-encoded. MIME-aware mail readers would show this header using the
-embedded ISO-8859-1 character.
-
-\versionadded{2.2.2}
-
-Here is the \class{Header} class description:
-
-\begin{classdesc}{Header}{\optional{s\optional{, charset\optional{,
- maxlinelen\optional{, header_name\optional{, continuation_ws\optional{,
- errors}}}}}}}
-Create a MIME-compliant header that can contain strings in different
-character sets.
-
-Optional \var{s} is the initial header value. If \code{None} (the
-default), the initial header value is not set. You can later append
-to the header with \method{append()} method calls. \var{s} may be a
-byte string or a Unicode string, but see the \method{append()}
-documentation for semantics.
-
-Optional \var{charset} serves two purposes: it has the same meaning as
-the \var{charset} argument to the \method{append()} method. It also
-sets the default character set for all subsequent \method{append()}
-calls that omit the \var{charset} argument. If \var{charset} is not
-provided in the constructor (the default), the \code{us-ascii}
-character set is used both as \var{s}'s initial charset and as the
-default for subsequent \method{append()} calls.
-
-The maximum line length can be specified explicit via
-\var{maxlinelen}. For splitting the first line to a shorter value (to
-account for the field header which isn't included in \var{s},
-e.g. \mailheader{Subject}) pass in the name of the field in
-\var{header_name}. The default \var{maxlinelen} is 76, and the
-default value for \var{header_name} is \code{None}, meaning it is not
-taken into account for the first line of a long, split header.
-
-Optional \var{continuation_ws} must be \rfc{2822}-compliant folding
-whitespace, and is usually either a space or a hard tab character.
-This character will be prepended to continuation lines.
-\end{classdesc}
-
-Optional \var{errors} is passed straight through to the
-\method{append()} method.
-
-\begin{methoddesc}[Header]{append}{s\optional{, charset\optional{, errors}}}
-Append the string \var{s} to the MIME header.
-
-Optional \var{charset}, if given, should be a \class{Charset} instance
-(see \refmodule{email.Charset}) or the name of a character set, which
-will be converted to a \class{Charset} instance. A value of
-\code{None} (the default) means that the \var{charset} given in the
-constructor is used.
-
-\var{s} may be a byte string or a Unicode string. If it is a byte
-string (i.e. \code{isinstance(s, str)} is true), then
-\var{charset} is the encoding of that byte string, and a
-\exception{UnicodeError} will be raised if the string cannot be
-decoded with that character set.
-
-If \var{s} is a Unicode string, then \var{charset} is a hint
-specifying the character set of the characters in the string. In this
-case, when producing an \rfc{2822}-compliant header using \rfc{2047}
-rules, the Unicode string will be encoded using the following charsets
-in order: \code{us-ascii}, the \var{charset} hint, \code{utf-8}. The
-first character set to not provoke a \exception{UnicodeError} is used.
-
-Optional \var{errors} is passed through to any \function{unicode()} or
-\function{ustr.encode()} call, and defaults to ``strict''.
-\end{methoddesc}
-
-\begin{methoddesc}[Header]{encode}{\optional{splitchars}}
-Encode a message header into an RFC-compliant format, possibly
-wrapping long lines and encapsulating non-\ASCII{} parts in base64 or
-quoted-printable encodings. Optional \var{splitchars} is a string
-containing characters to split long ASCII lines on, in rough support
-of \rfc{2822}'s \emph{highest level syntactic breaks}. This doesn't
-affect \rfc{2047} encoded lines.
-\end{methoddesc}
-
-The \class{Header} class also provides a number of methods to support
-standard operators and built-in functions.
-
-\begin{methoddesc}[Header]{__str__}{}
-A synonym for \method{Header.encode()}. Useful for
-\code{str(aHeader)}.
-\end{methoddesc}
-
-\begin{methoddesc}[Header]{__unicode__}{}
-A helper for the built-in \function{unicode()} function. Returns the
-header as a Unicode string.
-\end{methoddesc}
-
-\begin{methoddesc}[Header]{__eq__}{other}
-This method allows you to compare two \class{Header} instances for equality.
-\end{methoddesc}
-
-\begin{methoddesc}[Header]{__ne__}{other}
-This method allows you to compare two \class{Header} instances for inequality.
-\end{methoddesc}
-
-The \module{email.Header} module also provides the following
-convenient functions.
-
-\begin{funcdesc}{decode_header}{header}
-Decode a message header value without converting the character set.
-The header value is in \var{header}.
-
-This function returns a list of \code{(decoded_string, charset)} pairs
-containing each of the decoded parts of the header. \var{charset} is
-\code{None} for non-encoded parts of the header, otherwise a lower
-case string containing the name of the character set specified in the
-encoded string.
-
-Here's an example:
-
-\begin{verbatim}
->>> from email.Header import decode_header
->>> decode_header('=?iso-8859-1?q?p=F6stal?=')
-[('p\\xf6stal', 'iso-8859-1')]
-\end{verbatim}
-\end{funcdesc}
-
-\begin{funcdesc}{make_header}{decoded_seq\optional{, maxlinelen\optional{,
- header_name\optional{, continuation_ws}}}}
-Create a \class{Header} instance from a sequence of pairs as returned
-by \function{decode_header()}.
-
-\function{decode_header()} takes a header value string and returns a
-sequence of pairs of the format \code{(decoded_string, charset)} where
-\var{charset} is the name of the character set.
-
-This function takes one of those sequence of pairs and returns a
-\class{Header} instance. Optional \var{maxlinelen},
-\var{header_name}, and \var{continuation_ws} are as in the
-\class{Header} constructor.
-\end{funcdesc}
diff --git a/Doc/lib/emailiter.tex b/Doc/lib/emailiter.tex
deleted file mode 100644
index d1a8f98064..0000000000
--- a/Doc/lib/emailiter.tex
+++ /dev/null
@@ -1,65 +0,0 @@
-\declaremodule{standard}{email.Iterators}
-\modulesynopsis{Iterate over a message object tree.}
-
-Iterating over a message object tree is fairly easy with the
-\method{Message.walk()} method. The \module{email.Iterators} module
-provides some useful higher level iterations over message object
-trees.
-
-\begin{funcdesc}{body_line_iterator}{msg\optional{, decode}}
-This iterates over all the payloads in all the subparts of \var{msg},
-returning the string payloads line-by-line. It skips over all the
-subpart headers, and it skips over any subpart with a payload that
-isn't a Python string. This is somewhat equivalent to reading the
-flat text representation of the message from a file using
-\method{readline()}, skipping over all the intervening headers.
-
-Optional \var{decode} is passed through to \method{Message.get_payload()}.
-\end{funcdesc}
-
-\begin{funcdesc}{typed_subpart_iterator}{msg\optional{,
- maintype\optional{, subtype}}}
-This iterates over all the subparts of \var{msg}, returning only those
-subparts that match the MIME type specified by \var{maintype} and
-\var{subtype}.
-
-Note that \var{subtype} is optional; if omitted, then subpart MIME
-type matching is done only with the main type. \var{maintype} is
-optional too; it defaults to \mimetype{text}.
-
-Thus, by default \function{typed_subpart_iterator()} returns each
-subpart that has a MIME type of \mimetype{text/*}.
-\end{funcdesc}
-
-The following function has been added as a useful debugging tool. It
-should \emph{not} be considered part of the supported public interface
-for the package.
-
-\begin{funcdesc}{_structure}{msg\optional{, fp\optional{, level}}}
-Prints an indented representation of the content types of the
-message object structure. For example:
-
-\begin{verbatim}
->>> msg = email.message_from_file(somefile)
->>> _structure(msg)
-multipart/mixed
- text/plain
- text/plain
- multipart/digest
- message/rfc822
- text/plain
- message/rfc822
- text/plain
- message/rfc822
- text/plain
- message/rfc822
- text/plain
- message/rfc822
- text/plain
- text/plain
-\end{verbatim}
-
-Optional \var{fp} is a file-like object to print the output to. It
-must be suitable for Python's extended print statement. \var{level}
-is used internally.
-\end{funcdesc}
diff --git a/Doc/lib/emailmessage.tex b/Doc/lib/emailmessage.tex
deleted file mode 100644
index f580edfc91..0000000000
--- a/Doc/lib/emailmessage.tex
+++ /dev/null
@@ -1,603 +0,0 @@
-\declaremodule{standard}{email.Message}
-\modulesynopsis{The base class representing email messages.}
-
-The central class in the \module{email} package is the
-\class{Message} class; it is the base class for the \module{email}
-object model. \class{Message} provides the core functionality for
-setting and querying header fields, and for accessing message bodies.
-
-Conceptually, a \class{Message} object consists of \emph{headers} and
-\emph{payloads}. Headers are \rfc{2822} style field names and
-values where the field name and value are separated by a colon. The
-colon is not part of either the field name or the field value.
-
-Headers are stored and returned in case-preserving form but are
-matched case-insensitively. There may also be a single envelope
-header, also known as the \emph{Unix-From} header or the
-\code{From_} header. The payload is either a string in the case of
-simple message objects or a list of \class{Message} objects for
-MIME container documents (e.g. \mimetype{multipart/*} and
-\mimetype{message/rfc822}).
-
-\class{Message} objects provide a mapping style interface for
-accessing the message headers, and an explicit interface for accessing
-both the headers and the payload. It provides convenience methods for
-generating a flat text representation of the message object tree, for
-accessing commonly used header parameters, and for recursively walking
-over the object tree.
-
-Here are the methods of the \class{Message} class:
-
-\begin{classdesc}{Message}{}
-The constructor takes no arguments.
-\end{classdesc}
-
-\begin{methoddesc}[Message]{as_string}{\optional{unixfrom}}
-Return the entire message flatten as a string. When optional
-\var{unixfrom} is \code{True}, the envelope header is included in the
-returned string. \var{unixfrom} defaults to \code{False}.
-
-Note that this method is provided as a convenience and may not always
-format the message the way you want. For more flexibility,
-instantiate a \class{Generator} instance and use its
-\method{flatten()} method directly. For example:
-
-\begin{verbatim}
-from cStringIO import StringIO
-from email.Generator import Generator
-fp = StringIO()
-g = Generator(mangle_from_=False, maxheaderlen=60)
-g.flatten(msg)
-text = fp.getvalue()
-\end{verbatim}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{__str__}{}
-Equivalent to \method{as_string(unixfrom=True)}.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{is_multipart}{}
-Return \code{True} if the message's payload is a list of
-sub-\class{Message} objects, otherwise return \code{False}. When
-\method{is_multipart()} returns False, the payload should be a string
-object.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{set_unixfrom}{unixfrom}
-Set the message's envelope header to \var{unixfrom}, which should be a string.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_unixfrom}{}
-Return the message's envelope header. Defaults to \code{None} if the
-envelope header was never set.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{attach}{payload}
-Add the given \var{payload} to the current payload, which must be
-\code{None} or a list of \class{Message} objects before the call.
-After the call, the payload will always be a list of \class{Message}
-objects. If you want to set the payload to a scalar object (e.g. a
-string), use \method{set_payload()} instead.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_payload}{\optional{i\optional{, decode}}}
-Return a reference the current payload, which will be a list of
-\class{Message} objects when \method{is_multipart()} is \code{True}, or a
-string when \method{is_multipart()} is \code{False}. If the
-payload is a list and you mutate the list object, you modify the
-message's payload in place.
-
-With optional argument \var{i}, \method{get_payload()} will return the
-\var{i}-th element of the payload, counting from zero, if
-\method{is_multipart()} is \code{True}. An \exception{IndexError}
-will be raised if \var{i} is less than 0 or greater than or equal to
-the number of items in the payload. If the payload is a string
-(i.e. \method{is_multipart()} is \code{False}) and \var{i} is given, a
-\exception{TypeError} is raised.
-
-Optional \var{decode} is a flag indicating whether the payload should be
-decoded or not, according to the \mailheader{Content-Transfer-Encoding} header.
-When \code{True} and the message is not a multipart, the payload will be
-decoded if this header's value is \samp{quoted-printable} or
-\samp{base64}. If some other encoding is used, or
-\mailheader{Content-Transfer-Encoding} header is
-missing, or if the payload has bogus base64 data, the payload is
-returned as-is (undecoded). If the message is a multipart and the
-\var{decode} flag is \code{True}, then \code{None} is returned. The
-default for \var{decode} is \code{False}.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{set_payload}{payload\optional{, charset}}
-Set the entire message object's payload to \var{payload}. It is the
-client's responsibility to ensure the payload invariants. Optional
-\var{charset} sets the message's default character set; see
-\method{set_charset()} for details.
-
-\versionchanged[\var{charset} argument added]{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{set_charset}{charset}
-Set the character set of the payload to \var{charset}, which can
-either be a \class{Charset} instance (see \refmodule{email.Charset}), a
-string naming a character set,
-or \code{None}. If it is a string, it will be converted to a
-\class{Charset} instance. If \var{charset} is \code{None}, the
-\code{charset} parameter will be removed from the
-\mailheader{Content-Type} header. Anything else will generate a
-\exception{TypeError}.
-
-The message will be assumed to be of type \mimetype{text/*} encoded with
-\code{charset.input_charset}. It will be converted to
-\code{charset.output_charset}
-and encoded properly, if needed, when generating the plain text
-representation of the message. MIME headers
-(\mailheader{MIME-Version}, \mailheader{Content-Type},
-\mailheader{Content-Transfer-Encoding}) will be added as needed.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_charset}{}
-Return the \class{Charset} instance associated with the message's payload.
-\versionadded{2.2.2}
-\end{methoddesc}
-
-The following methods implement a mapping-like interface for accessing
-the message's \rfc{2822} headers. Note that there are some
-semantic differences between these methods and a normal mapping
-(i.e. dictionary) interface. For example, in a dictionary there are
-no duplicate keys, but here there may be duplicate message headers. Also,
-in dictionaries there is no guaranteed order to the keys returned by
-\method{keys()}, but in a \class{Message} object, headers are always
-returned in the order they appeared in the original message, or were
-added to the message later. Any header deleted and then re-added are
-always appended to the end of the header list.
-
-These semantic differences are intentional and are biased toward
-maximal convenience.
-
-Note that in all cases, any envelope header present in the message is
-not included in the mapping interface.
-
-\begin{methoddesc}[Message]{__len__}{}
-Return the total number of headers, including duplicates.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{__contains__}{name}
-Return true if the message object has a field named \var{name}.
-Matching is done case-insensitively and \var{name} should not include the
-trailing colon. Used for the \code{in} operator,
-e.g.:
-
-\begin{verbatim}
-if 'message-id' in myMessage:
- print 'Message-ID:', myMessage['message-id']
-\end{verbatim}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{__getitem__}{name}
-Return the value of the named header field. \var{name} should not
-include the colon field separator. If the header is missing,
-\code{None} is returned; a \exception{KeyError} is never raised.
-
-Note that if the named field appears more than once in the message's
-headers, exactly which of those field values will be returned is
-undefined. Use the \method{get_all()} method to get the values of all
-the extant named headers.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{__setitem__}{name, val}
-Add a header to the message with field name \var{name} and value
-\var{val}. The field is appended to the end of the message's existing
-fields.
-
-Note that this does \emph{not} overwrite or delete any existing header
-with the same name. If you want to ensure that the new header is the
-only one present in the message with field name
-\var{name}, delete the field first, e.g.:
-
-\begin{verbatim}
-del msg['subject']
-msg['subject'] = 'Python roolz!'
-\end{verbatim}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{__delitem__}{name}
-Delete all occurrences of the field with name \var{name} from the
-message's headers. No exception is raised if the named field isn't
-present in the headers.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{has_key}{name}
-Return true if the message contains a header field named \var{name},
-otherwise return false.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{keys}{}
-Return a list of all the message's header field names.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{values}{}
-Return a list of all the message's field values.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{items}{}
-Return a list of 2-tuples containing all the message's field headers
-and values.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get}{name\optional{, failobj}}
-Return the value of the named header field. This is identical to
-\method{__getitem__()} except that optional \var{failobj} is returned
-if the named header is missing (defaults to \code{None}).
-\end{methoddesc}
-
-Here are some additional useful methods:
-
-\begin{methoddesc}[Message]{get_all}{name\optional{, failobj}}
-Return a list of all the values for the field named \var{name}.
-If there are no such named headers in the message, \var{failobj} is
-returned (defaults to \code{None}).
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{add_header}{_name, _value, **_params}
-Extended header setting. This method is similar to
-\method{__setitem__()} except that additional header parameters can be
-provided as keyword arguments. \var{_name} is the header field to add
-and \var{_value} is the \emph{primary} value for the header.
-
-For each item in the keyword argument dictionary \var{_params}, the
-key is taken as the parameter name, with underscores converted to
-dashes (since dashes are illegal in Python identifiers). Normally,
-the parameter will be added as \code{key="value"} unless the value is
-\code{None}, in which case only the key will be added.
-
-Here's an example:
-
-\begin{verbatim}
-msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')
-\end{verbatim}
-
-This will add a header that looks like
-
-\begin{verbatim}
-Content-Disposition: attachment; filename="bud.gif"
-\end{verbatim}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{replace_header}{_name, _value}
-Replace a header. Replace the first header found in the message that
-matches \var{_name}, retaining header order and field name case. If
-no matching header was found, a \exception{KeyError} is raised.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_content_type}{}
-Return the message's content type. The returned string is coerced to
-lower case of the form \mimetype{maintype/subtype}. If there was no
-\mailheader{Content-Type} header in the message the default type as
-given by \method{get_default_type()} will be returned. Since
-according to \rfc{2045}, messages always have a default type,
-\method{get_content_type()} will always return a value.
-
-\rfc{2045} defines a message's default type to be
-\mimetype{text/plain} unless it appears inside a
-\mimetype{multipart/digest} container, in which case it would be
-\mimetype{message/rfc822}. If the \mailheader{Content-Type} header
-has an invalid type specification, \rfc{2045} mandates that the
-default type be \mimetype{text/plain}.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_content_maintype}{}
-Return the message's main content type. This is the
-\mimetype{maintype} part of the string returned by
-\method{get_content_type()}.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_content_subtype}{}
-Return the message's sub-content type. This is the \mimetype{subtype}
-part of the string returned by \method{get_content_type()}.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_default_type}{}
-Return the default content type. Most messages have a default content
-type of \mimetype{text/plain}, except for messages that are subparts
-of \mimetype{multipart/digest} containers. Such subparts have a
-default content type of \mimetype{message/rfc822}.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{set_default_type}{ctype}
-Set the default content type. \var{ctype} should either be
-\mimetype{text/plain} or \mimetype{message/rfc822}, although this is
-not enforced. The default content type is not stored in the
-\mailheader{Content-Type} header.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_params}{\optional{failobj\optional{,
- header\optional{, unquote}}}}
-Return the message's \mailheader{Content-Type} parameters, as a list. The
-elements of the returned list are 2-tuples of key/value pairs, as
-split on the \character{=} sign. The left hand side of the
-\character{=} is the key, while the right hand side is the value. If
-there is no \character{=} sign in the parameter the value is the empty
-string, otherwise the value is as described in \method{get_param()} and is
-unquoted if optional \var{unquote} is \code{True} (the default).
-
-Optional \var{failobj} is the object to return if there is no
-\mailheader{Content-Type} header. Optional \var{header} is the header to
-search instead of \mailheader{Content-Type}.
-
-\versionchanged[\var{unquote} argument added]{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_param}{param\optional{,
- failobj\optional{, header\optional{, unquote}}}}
-Return the value of the \mailheader{Content-Type} header's parameter
-\var{param} as a string. If the message has no \mailheader{Content-Type}
-header or if there is no such parameter, then \var{failobj} is
-returned (defaults to \code{None}).
-
-Optional \var{header} if given, specifies the message header to use
-instead of \mailheader{Content-Type}.
-
-Parameter keys are always compared case insensitively. The return
-value can either be a string, or a 3-tuple if the parameter was
-\rfc{2231} encoded. When it's a 3-tuple, the elements of the value are of
-the form \code{(CHARSET, LANGUAGE, VALUE)}, where \code{LANGUAGE} may
-be the empty string. Your application should be prepared to deal with
-3-tuple return values, which it can convert to a Unicode string like
-so:
-
-\begin{verbatim}
-param = msg.get_param('foo')
-if isinstance(param, tuple):
- param = unicode(param[2], param[0])
-\end{verbatim}
-
-In any case, the parameter value (either the returned string, or the
-\code{VALUE} item in the 3-tuple) is always unquoted, unless
-\var{unquote} is set to \code{False}.
-
-\versionchanged[\var{unquote} argument added, and 3-tuple return value
-possible]{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{set_param}{param, value\optional{,
- header\optional{, requote\optional{, charset\optional{, language}}}}}
-
-Set a parameter in the \mailheader{Content-Type} header. If the
-parameter already exists in the header, its value will be replaced
-with \var{value}. If the \mailheader{Content-Type} header as not yet
-been defined for this message, it will be set to \mimetype{text/plain}
-and the new parameter value will be appended as per \rfc{2045}.
-
-Optional \var{header} specifies an alternative header to
-\mailheader{Content-Type}, and all parameters will be quoted as
-necessary unless optional \var{requote} is \code{False} (the default
-is \code{True}).
-
-If optional \var{charset} is specified, the parameter will be encoded
-according to \rfc{2231}. Optional \var{language} specifies the RFC
-2231 language, defaulting to the empty string. Both \var{charset} and
-\var{language} should be strings.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{del_param}{param\optional{, header\optional{,
- requote}}}
-Remove the given parameter completely from the
-\mailheader{Content-Type} header. The header will be re-written in
-place without the parameter or its value. All values will be quoted
-as necessary unless \var{requote} is \code{False} (the default is
-\code{True}). Optional \var{header} specifies an alternative to
-\mailheader{Content-Type}.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{set_type}{type\optional{, header}\optional{,
- requote}}
-Set the main type and subtype for the \mailheader{Content-Type}
-header. \var{type} must be a string in the form
-\mimetype{maintype/subtype}, otherwise a \exception{ValueError} is
-raised.
-
-This method replaces the \mailheader{Content-Type} header, keeping all
-the parameters in place. If \var{requote} is \code{False}, this
-leaves the existing header's quoting as is, otherwise the parameters
-will be quoted (the default).
-
-An alternative header can be specified in the \var{header} argument.
-When the \mailheader{Content-Type} header is set a
-\mailheader{MIME-Version} header is also added.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_filename}{\optional{failobj}}
-Return the value of the \code{filename} parameter of the
-\mailheader{Content-Disposition} header of the message, or \var{failobj} if
-either the header is missing, or has no \code{filename} parameter.
-The returned string will always be unquoted as per
-\method{Utils.unquote()}.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_boundary}{\optional{failobj}}
-Return the value of the \code{boundary} parameter of the
-\mailheader{Content-Type} header of the message, or \var{failobj} if either
-the header is missing, or has no \code{boundary} parameter. The
-returned string will always be unquoted as per
-\method{Utils.unquote()}.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{set_boundary}{boundary}
-Set the \code{boundary} parameter of the \mailheader{Content-Type}
-header to \var{boundary}. \method{set_boundary()} will always quote
-\var{boundary} if necessary. A \exception{HeaderParseError} is raised
-if the message object has no \mailheader{Content-Type} header.
-
-Note that using this method is subtly different than deleting the old
-\mailheader{Content-Type} header and adding a new one with the new boundary
-via \method{add_header()}, because \method{set_boundary()} preserves the
-order of the \mailheader{Content-Type} header in the list of headers.
-However, it does \emph{not} preserve any continuation lines which may
-have been present in the original \mailheader{Content-Type} header.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_content_charset}{\optional{failobj}}
-Return the \code{charset} parameter of the \mailheader{Content-Type}
-header, coerced to lower case. If there is no
-\mailheader{Content-Type} header, or if that header has no
-\code{charset} parameter, \var{failobj} is returned.
-
-Note that this method differs from \method{get_charset()} which
-returns the \class{Charset} instance for the default encoding of the
-message body.
-
-\versionadded{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_charsets}{\optional{failobj}}
-Return a list containing the character set names in the message. If
-the message is a \mimetype{multipart}, then the list will contain one
-element for each subpart in the payload, otherwise, it will be a list
-of length 1.
-
-Each item in the list will be a string which is the value of the
-\code{charset} parameter in the \mailheader{Content-Type} header for the
-represented subpart. However, if the subpart has no
-\mailheader{Content-Type} header, no \code{charset} parameter, or is not of
-the \mimetype{text} main MIME type, then that item in the returned list
-will be \var{failobj}.
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{walk}{}
-The \method{walk()} method is an all-purpose generator which can be
-used to iterate over all the parts and subparts of a message object
-tree, in depth-first traversal order. You will typically use
-\method{walk()} as the iterator in a \code{for} loop; each
-iteration returns the next subpart.
-
-Here's an example that prints the MIME type of every part of a
-multipart message structure:
-
-\begin{verbatim}
->>> for part in msg.walk():
->>> print part.get_content_type()
-multipart/report
-text/plain
-message/delivery-status
-text/plain
-text/plain
-message/rfc822
-\end{verbatim}
-\end{methoddesc}
-
-\class{Message} objects can also optionally contain two instance
-attributes, which can be used when generating the plain text of a MIME
-message.
-
-\begin{datadesc}{preamble}
-The format of a MIME document allows for some text between the blank
-line following the headers, and the first multipart boundary string.
-Normally, this text is never visible in a MIME-aware mail reader
-because it falls outside the standard MIME armor. However, when
-viewing the raw text of the message, or when viewing the message in a
-non-MIME aware reader, this text can become visible.
-
-The \var{preamble} attribute contains this leading extra-armor text
-for MIME documents. When the \class{Parser} discovers some text after
-the headers but before the first boundary string, it assigns this text
-to the message's \var{preamble} attribute. When the \class{Generator}
-is writing out the plain text representation of a MIME message, and it
-finds the message has a \var{preamble} attribute, it will write this
-text in the area between the headers and the first boundary. See
-\refmodule{email.Parser} and \refmodule{email.Generator} for details.
-
-Note that if the message object has no preamble, the
-\var{preamble} attribute will be \code{None}.
-\end{datadesc}
-
-\begin{datadesc}{epilogue}
-The \var{epilogue} attribute acts the same way as the \var{preamble}
-attribute, except that it contains text that appears between the last
-boundary and the end of the message.
-
-One note: when generating the flat text for a \mimetype{multipart}
-message that has no \var{epilogue} (using the standard
-\class{Generator} class), no newline is added after the closing
-boundary line. If the message object has an \var{epilogue} and its
-value does not start with a newline, a newline is printed after the
-closing boundary. This seems a little clumsy, but it makes the most
-practical sense. The upshot is that if you want to ensure that a
-newline get printed after your closing \mimetype{multipart} boundary,
-set the \var{epilogue} to the empty string.
-\end{datadesc}
-
-\subsubsection{Deprecated methods}
-
-The following methods are deprecated in \module{email} version 2.
-They are documented here for completeness.
-
-\begin{methoddesc}[Message]{add_payload}{payload}
-Add \var{payload} to the message object's existing payload. If, prior
-to calling this method, the object's payload was \code{None}
-(i.e. never before set), then after this method is called, the payload
-will be the argument \var{payload}.
-
-If the object's payload was already a list
-(i.e. \method{is_multipart()} returns 1), then \var{payload} is
-appended to the end of the existing payload list.
-
-For any other type of existing payload, \method{add_payload()} will
-transform the new payload into a list consisting of the old payload
-and \var{payload}, but only if the document is already a MIME
-multipart document. This condition is satisfied if the message's
-\mailheader{Content-Type} header's main type is either
-\mimetype{multipart}, or there is no \mailheader{Content-Type}
-header. In any other situation,
-\exception{MultipartConversionError} is raised.
-
-\deprecated{2.2.2}{Use the \method{attach()} method instead.}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_type}{\optional{failobj}}
-Return the message's content type, as a string of the form
-\mimetype{maintype/subtype} as taken from the
-\mailheader{Content-Type} header.
-The returned string is coerced to lowercase.
-
-If there is no \mailheader{Content-Type} header in the message,
-\var{failobj} is returned (defaults to \code{None}).
-
-\deprecated{2.2.2}{Use the \method{get_content_type()} method instead.}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_main_type}{\optional{failobj}}
-Return the message's \emph{main} content type. This essentially returns the
-\var{maintype} part of the string returned by \method{get_type()}, with the
-same semantics for \var{failobj}.
-
-\deprecated{2.2.2}{Use the \method{get_content_maintype()} method instead.}
-\end{methoddesc}
-
-\begin{methoddesc}[Message]{get_subtype}{\optional{failobj}}
-Return the message's sub-content type. This essentially returns the
-\var{subtype} part of the string returned by \method{get_type()}, with the
-same semantics for \var{failobj}.
-
-\deprecated{2.2.2}{Use the \method{get_content_subtype()} method instead.}
-\end{methoddesc}
-
diff --git a/Doc/lib/emailmimebase.tex b/Doc/lib/emailmimebase.tex
deleted file mode 100644
index 3318d6aa8d..0000000000
--- a/Doc/lib/emailmimebase.tex
+++ /dev/null
@@ -1,158 +0,0 @@
-Ordinarily, you get a message object structure by passing a file or
-some text to a parser, which parses the text and returns the root
-message object. However you can also build a complete message
-structure from scratch, or even individual \class{Message} objects by
-hand. In fact, you can also take an existing structure and add new
-\class{Message} objects, move them around, etc. This makes a very
-convenient interface for slicing-and-dicing MIME messages.
-
-You can create a new object structure by creating \class{Message}
-instances, adding attachments and all the appropriate headers manually.
-For MIME messages though, the \module{email} package provides some
-convenient subclasses to make things easier. Each of these classes
-should be imported from a module with the same name as the class, from
-within the \module{email} package. E.g.:
-
-\begin{verbatim}
-import email.MIMEImage.MIMEImage
-\end{verbatim}
-
-or
-
-\begin{verbatim}
-from email.MIMEText import MIMEText
-\end{verbatim}
-
-Here are the classes:
-
-\begin{classdesc}{MIMEBase}{_maintype, _subtype, **_params}
-This is the base class for all the MIME-specific subclasses of
-\class{Message}. Ordinarily you won't create instances specifically
-of \class{MIMEBase}, although you could. \class{MIMEBase} is provided
-primarily as a convenient base class for more specific MIME-aware
-subclasses.
-
-\var{_maintype} is the \mailheader{Content-Type} major type
-(e.g. \mimetype{text} or \mimetype{image}), and \var{_subtype} is the
-\mailheader{Content-Type} minor type
-(e.g. \mimetype{plain} or \mimetype{gif}). \var{_params} is a parameter
-key/value dictionary and is passed directly to
-\method{Message.add_header()}.
-
-The \class{MIMEBase} class always adds a \mailheader{Content-Type} header
-(based on \var{_maintype}, \var{_subtype}, and \var{_params}), and a
-\mailheader{MIME-Version} header (always set to \code{1.0}).
-\end{classdesc}
-
-\begin{classdesc}{MIMENonMultipart}{}
-A subclass of \class{MIMEBase}, this is an intermediate base class for
-MIME messages that are not \mimetype{multipart}. The primary purpose
-of this class is to prevent the use of the \method{attach()} method,
-which only makes sense for \mimetype{multipart} messages. If
-\method{attach()} is called, a \exception{MultipartConversionError}
-exception is raised.
-
-\versionadded{2.2.2}
-\end{classdesc}
-
-\begin{classdesc}{MIMEMultipart}{\optional{subtype\optional{,
- boundary\optional{, _subparts\optional{, _params}}}}}
-
-A subclass of \class{MIMEBase}, this is an intermediate base class for
-MIME messages that are \mimetype{multipart}. Optional \var{_subtype}
-defaults to \mimetype{mixed}, but can be used to specify the subtype
-of the message. A \mailheader{Content-Type} header of
-\mimetype{multipart/}\var{_subtype} will be added to the message
-object. A \mailheader{MIME-Version} header will also be added.
-
-Optional \var{boundary} is the multipart boundary string. When
-\code{None} (the default), the boundary is calculated when needed.
-
-\var{_subparts} is a sequence of initial subparts for the payload. It
-must be possible to convert this sequence to a list. You can always
-attach new subparts to the message by using the
-\method{Message.attach()} method.
-
-Additional parameters for the \mailheader{Content-Type} header are
-taken from the keyword arguments, or passed into the \var{_params}
-argument, which is a keyword dictionary.
-
-\versionadded{2.2.2}
-\end{classdesc}
-
-\begin{classdesc}{MIMEAudio}{_audiodata\optional{, _subtype\optional{,
- _encoder\optional{, **_params}}}}
-
-A subclass of \class{MIMENonMultipart}, the \class{MIMEAudio} class
-is used to create MIME message objects of major type \mimetype{audio}.
-\var{_audiodata} is a string containing the raw audio data. If this
-data can be decoded by the standard Python module \refmodule{sndhdr},
-then the subtype will be automatically included in the
-\mailheader{Content-Type} header. Otherwise you can explicitly specify the
-audio subtype via the \var{_subtype} parameter. If the minor type could
-not be guessed and \var{_subtype} was not given, then \exception{TypeError}
-is raised.
-
-Optional \var{_encoder} is a callable (i.e. function) which will
-perform the actual encoding of the audio data for transport. This
-callable takes one argument, which is the \class{MIMEAudio} instance.
-It should use \method{get_payload()} and \method{set_payload()} to
-change the payload to encoded form. It should also add any
-\mailheader{Content-Transfer-Encoding} or other headers to the message
-object as necessary. The default encoding is base64. See the
-\refmodule{email.Encoders} module for a list of the built-in encoders.
-
-\var{_params} are passed straight through to the base class constructor.
-\end{classdesc}
-
-\begin{classdesc}{MIMEImage}{_imagedata\optional{, _subtype\optional{,
- _encoder\optional{, **_params}}}}
-
-A subclass of \class{MIMENonMultipart}, the \class{MIMEImage} class is
-used to create MIME message objects of major type \mimetype{image}.
-\var{_imagedata} is a string containing the raw image data. If this
-data can be decoded by the standard Python module \refmodule{imghdr},
-then the subtype will be automatically included in the
-\mailheader{Content-Type} header. Otherwise you can explicitly specify the
-image subtype via the \var{_subtype} parameter. If the minor type could
-not be guessed and \var{_subtype} was not given, then \exception{TypeError}
-is raised.
-
-Optional \var{_encoder} is a callable (i.e. function) which will
-perform the actual encoding of the image data for transport. This
-callable takes one argument, which is the \class{MIMEImage} instance.
-It should use \method{get_payload()} and \method{set_payload()} to
-change the payload to encoded form. It should also add any
-\mailheader{Content-Transfer-Encoding} or other headers to the message
-object as necessary. The default encoding is base64. See the
-\refmodule{email.Encoders} module for a list of the built-in encoders.
-
-\var{_params} are passed straight through to the \class{MIMEBase}
-constructor.
-\end{classdesc}
-
-\begin{classdesc}{MIMEMessage}{_msg\optional{, _subtype}}
-A subclass of \class{MIMENonMultipart}, the \class{MIMEMessage} class
-is used to create MIME objects of main type \mimetype{message}.
-\var{_msg} is used as the payload, and must be an instance of class
-\class{Message} (or a subclass thereof), otherwise a
-\exception{TypeError} is raised.
-
-Optional \var{_subtype} sets the subtype of the message; it defaults
-to \mimetype{rfc822}.
-\end{classdesc}
-
-\begin{classdesc}{MIMEText}{_text\optional{, _subtype\optional{,
- _charset\optional{, _encoder}}}}
-
-A subclass of \class{MIMENonMultipart}, the \class{MIMEText} class is
-used to create MIME objects of major type \mimetype{text}.
-\var{_text} is the string for the payload. \var{_subtype} is the
-minor type and defaults to \mimetype{plain}. \var{_charset} is the
-character set of the text and is passed as a parameter to the
-\class{MIMENonMultipart} constructor; it defaults to \code{us-ascii}. No
-guessing or encoding is performed on the text data.
-
-\deprecated{2.2.2}{The \var{_encoding} argument has been deprecated.
-Encoding now happens implicitly based on the \var{_charset} argument.}
-\end{classdesc}
diff --git a/Doc/lib/emailparser.tex b/Doc/lib/emailparser.tex
deleted file mode 100644
index 706ecbbf1f..0000000000
--- a/Doc/lib/emailparser.tex
+++ /dev/null
@@ -1,152 +0,0 @@
-\declaremodule{standard}{email.Parser}
-\modulesynopsis{Parse flat text email messages to produce a message
- object structure.}
-
-Message object structures can be created in one of two ways: they can be
-created from whole cloth by instantiating \class{Message} objects and
-stringing them together via \method{attach()} and
-\method{set_payload()} calls, or they can be created by parsing a flat text
-representation of the email message.
-
-The \module{email} package provides a standard parser that understands
-most email document structures, including MIME documents. You can
-pass the parser a string or a file object, and the parser will return
-to you the root \class{Message} instance of the object structure. For
-simple, non-MIME messages the payload of this root object will likely
-be a string containing the text of the message. For MIME
-messages, the root object will return \code{True} from its
-\method{is_multipart()} method, and the subparts can be accessed via
-the \method{get_payload()} and \method{walk()} methods.
-
-Note that the parser can be extended in limited ways, and of course
-you can implement your own parser completely from scratch. There is
-no magical connection between the \module{email} package's bundled
-parser and the \class{Message} class, so your custom parser can create
-message object trees any way it finds necessary.
-
-The primary parser class is \class{Parser} which parses both the
-headers and the payload of the message. In the case of
-\mimetype{multipart} messages, it will recursively parse the body of
-the container message. Two modes of parsing are supported,
-\emph{strict} parsing, which will usually reject any non-RFC compliant
-message, and \emph{lax} parsing, which attempts to adjust for common
-MIME formatting problems.
-
-The \module{email.Parser} module also provides a second class, called
-\class{HeaderParser} which can be used if you're only interested in
-the headers of the message. \class{HeaderParser} can be much faster in
-these situations, since it does not attempt to parse the message body,
-instead setting the payload to the raw body as a string.
-\class{HeaderParser} has the same API as the \class{Parser} class.
-
-\subsubsection{Parser class API}
-
-\begin{classdesc}{Parser}{\optional{_class\optional{, strict}}}
-The constructor for the \class{Parser} class takes an optional
-argument \var{_class}. This must be a callable factory (such as a
-function or a class), and it is used whenever a sub-message object
-needs to be created. It defaults to \class{Message} (see
-\refmodule{email.Message}). The factory will be called without
-arguments.
-
-The optional \var{strict} flag specifies whether strict or lax parsing
-should be performed. Normally, when things like MIME terminating
-boundaries are missing, or when messages contain other formatting
-problems, the \class{Parser} will raise a
-\exception{MessageParseError}. However, when lax parsing is enabled,
-the \class{Parser} will attempt to work around such broken formatting
-to produce a usable message structure (this doesn't mean
-\exception{MessageParseError}s are never raised; some ill-formatted
-messages just can't be parsed). The \var{strict} flag defaults to
-\code{False} since lax parsing usually provides the most convenient
-behavior.
-
-\versionchanged[The \var{strict} flag was added]{2.2.2}
-\end{classdesc}
-
-The other public \class{Parser} methods are:
-
-\begin{methoddesc}[Parser]{parse}{fp\optional{, headersonly}}
-Read all the data from the file-like object \var{fp}, parse the
-resulting text, and return the root message object. \var{fp} must
-support both the \method{readline()} and the \method{read()} methods
-on file-like objects.
-
-The text contained in \var{fp} must be formatted as a block of \rfc{2822}
-style headers and header continuation lines, optionally preceded by a
-envelope header. The header block is terminated either by the
-end of the data or by a blank line. Following the header block is the
-body of the message (which may contain MIME-encoded subparts).
-
-Optional \var{headersonly} is as with the \method{parse()} method.
-
-\versionchanged[The \var{headersonly} flag was added]{2.2.2}
-\end{methoddesc}
-
-\begin{methoddesc}[Parser]{parsestr}{text\optional{, headersonly}}
-Similar to the \method{parse()} method, except it takes a string
-object instead of a file-like object. Calling this method on a string
-is exactly equivalent to wrapping \var{text} in a \class{StringIO}
-instance first and calling \method{parse()}.
-
-Optional \var{headersonly} is a flag specifying whether to stop
-parsing after reading the headers or not. The default is \code{False},
-meaning it parses the entire contents of the file.
-
-\versionchanged[The \var{headersonly} flag was added]{2.2.2}
-\end{methoddesc}
-
-Since creating a message object structure from a string or a file
-object is such a common task, two functions are provided as a
-convenience. They are available in the top-level \module{email}
-package namespace.
-
-\begin{funcdesc}{message_from_string}{s\optional{, _class\optional{, strict}}}
-Return a message object structure from a string. This is exactly
-equivalent to \code{Parser().parsestr(s)}. Optional \var{_class} and
-\var{strict} are interpreted as with the \class{Parser} class constructor.
-
-\versionchanged[The \var{strict} flag was added]{2.2.2}
-\end{funcdesc}
-
-\begin{funcdesc}{message_from_file}{fp\optional{, _class\optional{, strict}}}
-Return a message object structure tree from an open file object. This
-is exactly equivalent to \code{Parser().parse(fp)}. Optional
-\var{_class} and \var{strict} are interpreted as with the
-\class{Parser} class constructor.
-
-\versionchanged[The \var{strict} flag was added]{2.2.2}
-\end{funcdesc}
-
-Here's an example of how you might use this at an interactive Python
-prompt:
-
-\begin{verbatim}
->>> import email
->>> msg = email.message_from_string(myString)
-\end{verbatim}
-
-\subsubsection{Additional notes}
-
-Here are some notes on the parsing semantics:
-
-\begin{itemize}
-\item Most non-\mimetype{multipart} type messages are parsed as a single
- message object with a string payload. These objects will return
- \code{False} for \method{is_multipart()}. Their
- \method{get_payload()} method will return a string object.
-
-\item All \mimetype{multipart} type messages will be parsed as a
- container message object with a list of sub-message objects for
- their payload. The outer container message will return
- \code{True} for \method{is_multipart()} and their
- \method{get_payload()} method will return the list of
- \class{Message} subparts.
-
-\item Most messages with a content type of \mimetype{message/*}
- (e.g. \mimetype{message/deliver-status} and
- \mimetype{message/rfc822}) will also be parsed as container
- object containing a list payload of length 1. Their
- \method{is_multipart()} method will return \code{True}. The
- single element in the list payload will be a sub-message object.
-\end{itemize}
diff --git a/Doc/lib/emailutil.tex b/Doc/lib/emailutil.tex
deleted file mode 100644
index 80f0acfd37..0000000000
--- a/Doc/lib/emailutil.tex
+++ /dev/null
@@ -1,142 +0,0 @@
-\declaremodule{standard}{email.Utils}
-\modulesynopsis{Miscellaneous email package utilities.}
-
-There are several useful utilities provided with the \module{email}
-package.
-
-\begin{funcdesc}{quote}{str}
-Return a new string with backslashes in \var{str} replaced by two
-backslashes, and double quotes replaced by backslash-double quote.
-\end{funcdesc}
-
-\begin{funcdesc}{unquote}{str}
-Return a new string which is an \emph{unquoted} version of \var{str}.
-If \var{str} ends and begins with double quotes, they are stripped
-off. Likewise if \var{str} ends and begins with angle brackets, they
-are stripped off.
-\end{funcdesc}
-
-\begin{funcdesc}{parseaddr}{address}
-Parse address -- which should be the value of some address-containing
-field such as \mailheader{To} or \mailheader{Cc} -- into its constituent
-\emph{realname} and \emph{email address} parts. Returns a tuple of that
-information, unless the parse fails, in which case a 2-tuple of
-\code{('', '')} is returned.
-\end{funcdesc}
-
-\begin{funcdesc}{formataddr}{pair}
-The inverse of \method{parseaddr()}, this takes a 2-tuple of the form
-\code{(realname, email_address)} and returns the string value suitable
-for a \mailheader{To} or \mailheader{Cc} header. If the first element of
-\var{pair} is false, then the second element is returned unmodified.
-\end{funcdesc}
-
-\begin{funcdesc}{getaddresses}{fieldvalues}
-This method returns a list of 2-tuples of the form returned by
-\code{parseaddr()}. \var{fieldvalues} is a sequence of header field
-values as might be returned by \method{Message.get_all()}. Here's a
-simple example that gets all the recipients of a message:
-
-\begin{verbatim}
-from email.Utils import getaddresses
-
-tos = msg.get_all('to', [])
-ccs = msg.get_all('cc', [])
-resent_tos = msg.get_all('resent-to', [])
-resent_ccs = msg.get_all('resent-cc', [])
-all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)
-\end{verbatim}
-\end{funcdesc}
-
-\begin{funcdesc}{parsedate}{date}
-Attempts to parse a date according to the rules in \rfc{2822}.
-however, some mailers don't follow that format as specified, so
-\function{parsedate()} tries to guess correctly in such cases.
-\var{date} is a string containing an \rfc{2822} date, such as
-\code{"Mon, 20 Nov 1995 19:12:08 -0500"}. If it succeeds in parsing
-the date, \function{parsedate()} returns a 9-tuple that can be passed
-directly to \function{time.mktime()}; otherwise \code{None} will be
-returned. Note that fields 6, 7, and 8 of the result tuple are not
-usable.
-\end{funcdesc}
-
-\begin{funcdesc}{parsedate_tz}{date}
-Performs the same function as \function{parsedate()}, but returns
-either \code{None} or a 10-tuple; the first 9 elements make up a tuple
-that can be passed directly to \function{time.mktime()}, and the tenth
-is the offset of the date's timezone from UTC (which is the official
-term for Greenwich Mean Time)\footnote{Note that the sign of the timezone
-offset is the opposite of the sign of the \code{time.timezone}
-variable for the same timezone; the latter variable follows the
-\POSIX{} standard while this module follows \rfc{2822}.}. If the input
-string has no timezone, the last element of the tuple returned is
-\code{None}. Note that fields 6, 7, and 8 of the result tuple are not
-usable.
-\end{funcdesc}
-
-\begin{funcdesc}{mktime_tz}{tuple}
-Turn a 10-tuple as returned by \function{parsedate_tz()} into a UTC
-timestamp. It the timezone item in the tuple is \code{None}, assume
-local time. Minor deficiency: \function{mktime_tz()} interprets the
-first 8 elements of \var{tuple} as a local time and then compensates
-for the timezone difference. This may yield a slight error around
-changes in daylight savings time, though not worth worrying about for
-common use.
-\end{funcdesc}
-
-\begin{funcdesc}{formatdate}{\optional{timeval\optional{, localtime}}}
-Returns a date string as per \rfc{2822}, e.g.:
-
-\begin{verbatim}
-Fri, 09 Nov 2001 01:08:47 -0000
-\end{verbatim}
-
-Optional \var{timeval} if given is a floating point time value as
-accepted by \function{time.gmtime()} and \function{time.localtime()},
-otherwise the current time is used.
-
-Optional \var{localtime} is a flag that when \code{True}, interprets
-\var{timeval}, and returns a date relative to the local timezone
-instead of UTC, properly taking daylight savings time into account.
-The default is \code{False} meaning UTC is used.
-\end{funcdesc}
-
-\begin{funcdesc}{make_msgid}{\optional{idstring}}
-Returns a string suitable for an \rfc{2822}-compliant
-\mailheader{Message-ID} header. Optional \var{idstring} if given, is
-a string used to strengthen the uniqueness of the message id.
-\end{funcdesc}
-
-\begin{funcdesc}{decode_rfc2231}{s}
-Decode the string \var{s} according to \rfc{2231}.
-\end{funcdesc}
-
-\begin{funcdesc}{encode_rfc2231}{s\optional{, charset\optional{, language}}}
-Encode the string \var{s} according to \rfc{2231}. Optional
-\var{charset} and \var{language}, if given is the character set name
-and language name to use. If neither is given, \var{s} is returned
-as-is. If \var{charset} is given but \var{language} is not, the
-string is encoded using the empty string for \var{language}.
-\end{funcdesc}
-
-\begin{funcdesc}{decode_params}{params}
-Decode parameters list according to \rfc{2231}. \var{params} is a
-sequence of 2-tuples containing elements of the form
-\code{(content-type, string-value)}.
-\end{funcdesc}
-
-The following functions have been deprecated:
-
-\begin{funcdesc}{dump_address_pair}{pair}
-\deprecated{2.2.2}{Use \function{formataddr()} instead.}
-\end{funcdesc}
-
-\begin{funcdesc}{decode}{s}
-\deprecated{2.2.2}{Use \method{Header.decode_header()} instead.}
-\end{funcdesc}
-
-
-\begin{funcdesc}{encode}{s\optional{, charset\optional{, encoding}}}
-\deprecated{2.2.2}{Use \method{Header.encode()} instead.}
-\end{funcdesc}
-
diff --git a/Doc/lib/internet.tex b/Doc/lib/internet.tex
deleted file mode 100644
index 72ac4b308c..0000000000
--- a/Doc/lib/internet.tex
+++ /dev/null
@@ -1,13 +0,0 @@
-\chapter{Internet Protocols and Support \label{internet}}
-
-\index{WWW}
-\index{Internet}
-\index{World Wide Web}
-
-The modules described in this chapter implement Internet protocols and
-support for related technology. They are all implemented in Python.
-Most of these modules require the presence of the system-dependent
-module \refmodule{socket}\refbimodindex{socket}, which is currently
-supported on most popular platforms. Here is an overview:
-
-\localmoduletable
diff --git a/Doc/lib/language.tex b/Doc/lib/language.tex
deleted file mode 100644
index b593f0e1fc..0000000000
--- a/Doc/lib/language.tex
+++ /dev/null
@@ -1,10 +0,0 @@
-\chapter{Python Language Services
- \label{language}}
-
-Python provides a number of modules to assist in working with the
-Python language. These module support tokenizing, parsing, syntax
-analysis, bytecode disassembly, and various other facilities.
-
-These modules include:
-
-\localmoduletable
diff --git a/Doc/lib/lib.tex b/Doc/lib/lib.tex
deleted file mode 100644
index ba3442a7a6..0000000000
--- a/Doc/lib/lib.tex
+++ /dev/null
@@ -1,378 +0,0 @@
-\documentclass{manual}
-
-% NOTE: this file controls which chapters/sections of the library
-% manual are actually printed. It is easy to customize your manual
-% by commenting out sections that you're not interested in.
-
-\title{Python Library Reference}
-
-\input{boilerplate}
-
-\makeindex % tell \index to actually write the
- % .idx file
-\makemodindex % ... and the module index as well.
-
-
-\begin{document}
-
-\maketitle
-
-\ifhtml
-\chapter*{Front Matter\label{front}}
-\fi
-
-\input{copyright}
-
-\begin{abstract}
-
-\noindent
-Python is an extensible, interpreted, object-oriented programming
-language. It supports a wide range of applications, from simple text
-processing scripts to interactive Web browsers.
-
-While the \citetitle[../ref/ref.html]{Python Reference Manual}
-describes the exact syntax and semantics of the language, it does not
-describe the standard library that is distributed with the language,
-and which greatly enhances its immediate usability. This library
-contains built-in modules (written in C) that provide access to system
-functionality such as file I/O that would otherwise be inaccessible to
-Python programmers, as well as modules written in Python that provide
-standardized solutions for many problems that occur in everyday
-programming. Some of these modules are explicitly designed to
-encourage and enhance the portability of Python programs.
-
-This library reference manual documents Python's standard library, as
-well as many optional library modules (which may or may not be
-available, depending on whether the underlying platform supports them
-and on the configuration choices made at compile time). It also
-documents the standard types of the language and its built-in
-functions and exceptions, many of which are not or incompletely
-documented in the Reference Manual.
-
-This manual assumes basic knowledge about the Python language. For an
-informal introduction to Python, see the
-\citetitle[../tut/tut.html]{Python Tutorial}; the
-\citetitle[../ref/ref.html]{Python Reference Manual} remains the
-highest authority on syntactic and semantic questions. Finally, the
-manual entitled \citetitle[../ext/ext.html]{Extending and Embedding
-the Python Interpreter} describes how to add new extensions to Python
-and how to embed it in other applications.
-
-\end{abstract}
-
-\tableofcontents
-
- % Chapter title:
-
-\input{libintro} % Introduction
-
-\input{libobjs} % Built-in Types, Exceptions and Functions
-\input{libfuncs}
-\input{libstdtypes}
-\input{libexcs}
-\input{libconsts}
-
-\input{libpython} % Python Runtime Services
-\input{libsys}
-\input{libgc}
-\input{libweakref}
-\input{libfpectl}
-\input{libatexit}
-\input{libtypes}
-\input{libuserdict}
-\input{liboperator}
-\input{libinspect}
-\input{libtraceback}
-\input{liblinecache}
-\input{libpickle}
-\input{libcopyreg} % really copy_reg
-\input{libshelve}
-\input{libcopy}
-\input{libmarshal}
-\input{libwarnings}
-\input{libimp}
-\input{libpkgutil}
-\input{libcode}
-\input{libcodeop}
-\input{libpprint}
-\input{librepr}
-\input{libnew}
-\input{libsite}
-\input{libuser}
-\input{libbltin} % really __builtin__
-\input{libmain} % really __main__
-\input{libfuture} % really __future__
-
-\input{libstrings} % String Services
-\input{libstring}
-\input{libre}
-\input{libstruct}
-\input{libdifflib}
-\input{libfpformat}
-\input{libstringio}
-\input{libtextwrap}
-\input{libcodecs}
-\input{libunicodedata}
-\input{libstringprep}
-
-\input{libmisc} % Miscellaneous Services
-\input{libpydoc}
-\input{libdoctest}
-\input{libunittest}
-\input{libtest}
-\input{libmath}
-\input{libcmath}
-\input{librandom}
-\input{libwhrandom}
-\input{libbisect}
-\input{libheapq}
-\input{libarray}
-\input{libsets}
-\input{libitertools}
-\input{libcfgparser}
-\input{libfileinput}
-\input{libxreadlines}
-\input{libcalendar}
-\input{libcmd}
-\input{libshlex}
-
-\input{liballos} % Generic Operating System Services
-\input{libos}
-\input{libposixpath} % os.path
-\input{libdircache}
-\input{libstat}
-\input{libstatcache}
-\input{libstatvfs}
-\input{libfilecmp}
-\input{libpopen2}
-\input{libdatetime}
-\input{libtime}
-\input{libsched}
-\input{libmutex}
-\input{libgetpass}
-\input{libcurses}
-\input{libascii} % curses.ascii
-\input{libcursespanel}
-\input{libgetopt}
-\input{liboptparse}
-\input{libtempfile}
-\input{liberrno}
-\input{libglob}
-\input{libfnmatch}
-\input{libshutil}
-\input{liblocale}
-\input{libgettext}
-\input{liblogging}
-
-\input{libsomeos} % Optional Operating System Services
-\input{libsignal}
-\input{libsocket}
-\input{libselect}
-\input{libthread}
-\input{libthreading}
-\input{libdummythread}
-\input{libdummythreading}
-\input{libqueue}
-\input{libmmap}
-\input{libanydbm}
-\input{libdbhash}
-\input{libwhichdb}
-\input{libbsddb}
-\input{libzlib}
-\input{libgzip}
-\input{libbz2}
-\input{libzipfile}
-\input{libtarfile}
-\input{libreadline}
-\input{librlcompleter}
-
-\input{libunix} % UNIX Specific Services
-\input{libposix}
-\input{libpwd}
-\input{libgrp}
-\input{libcrypt}
-\input{libdl}
-\input{libdbm}
-\input{libgdbm}
-\input{libtermios}
-\input{libtty}
-\input{libpty}
-\input{libfcntl}
-\input{libpipes}
-\input{libposixfile}
-\input{libresource}
-\input{libnis}
-\input{libsyslog}
-\input{libcommands}
-
-\input{libpdb} % The Python Debugger
-
-\input{libprofile} % The Python Profiler
-\input{libhotshot} % New profiler
-\input{libtimeit}
-
-\input{internet} % Internet Protocols
-\input{libwebbrowser}
-\input{libcgi}
-\input{libcgitb}
-\input{liburllib}
-\input{liburllib2}
-\input{libhttplib}
-\input{libftplib}
-\input{libgopherlib}
-\input{libpoplib}
-\input{libimaplib}
-\input{libnntplib}
-\input{libsmtplib}
-\input{libtelnetlib}
-\input{liburlparse}
-\input{libsocksvr}
-\input{libbasehttp}
-\input{libsimplehttp}
-\input{libcgihttp}
-\input{libcookie}
-\input{libxmlrpclib}
-\input{libsimplexmlrpc}
-\input{libdocxmlrpc}
-\input{libasyncore}
-\input{libasynchat}
-
-\input{netdata} % Internet Data Handling
-\input{libformatter}
-
-% MIME & email stuff
-\input{email}
-\input{libmailcap}
-\input{libmailbox}
-\input{libmhlib}
-\input{libmimetools}
-\input{libmimetypes}
-\input{libmimewriter}
-\input{libmimify}
-\input{libmultifile}
-\input{librfc822}
-
-% encoding stuff
-\input{libbase64}
-\input{libbinascii}
-\input{libbinhex}
-\input{libquopri}
-\input{libuu}
-\input{libxdrlib}
-
-% file formats
-\input{libnetrc}
-\input{librobotparser}
-\input{libcsv}
-
-\input{markup} % Structured Markup Processing Tools
-\input{libhtmlparser}
-\input{libsgmllib}
-\input{libhtmllib}
-\input{libpyexpat}
-\input{xmldom}
-\input{xmldomminidom}
-\input{xmldompulldom}
-\input{xmlsax}
-\input{xmlsaxhandler}
-\input{xmlsaxutils}
-\input{xmlsaxreader}
-\input{libxmllib}
-
-\input{libmm} % Multimedia Services
-\input{libaudioop}
-\input{libimageop}
-\input{libaifc}
-\input{libsunau}
-\input{libwave}
-\input{libchunk}
-\input{libcolorsys}
-\input{librgbimg}
-\input{libimghdr}
-\input{libsndhdr}
-\input{libossaudiodev}
-
-\input{libcrypto} % Cryptographic Services
-\input{libhmac}
-\input{libmd5}
-\input{libsha}
-\input{libmpz}
-\input{librotor}
-
-\input{tkinter}
-
-\input{librestricted} % Restricted Execution
-\input{librexec}
-\input{libbastion}
-
-\input{language} % Python Language Services
-\input{libparser}
-\input{libsymbol}
-\input{libtoken}
-\input{libkeyword}
-\input{libtokenize}
-\input{libtabnanny}
-\input{libpyclbr}
-\input{libpycompile} % really py_compile
-\input{libcompileall}
-\input{libdis}
-\input{distutils}
-
-\input{compiler} % compiler package
-
-%\input{libamoeba} % AMOEBA ONLY
-
-%\input{libstdwin} % STDWIN ONLY
-
-\input{libsgi} % SGI IRIX ONLY
-\input{libal}
-\input{libcd}
-\input{libfl}
-\input{libfm}
-\input{libgl}
-\input{libimgfile}
-\input{libjpeg}
-%\input{libpanel}
-
-\input{libsun} % SUNOS ONLY
-\input{libsunaudio}
-
-\input{windows} % MS Windows ONLY
-\input{libmsvcrt}
-\input{libwinreg}
-\input{libwinsound}
-
-\appendix
-\input{libundoc}
-
-%\chapter{Obsolete Modules}
-%\input{libcmpcache}
-%\input{libcmp}
-%\input{libni}
-%\input{librand}
-%\input{libregex}
-%\input{libregsub}
-
-\chapter{Reporting Bugs}
-\input{reportingbugs}
-
-\chapter{History and License}
-\input{license}
-
-%
-% The ugly "%begin{latexonly}" pseudo-environments are really just to
-% keep LaTeX2HTML quiet during the \renewcommand{} macros; they're
-% not really valuable.
-%
-
-%begin{latexonly}
-\renewcommand{\indexname}{Module Index}
-%end{latexonly}
-\input{modlib.ind} % Module Index
-
-%begin{latexonly}
-\renewcommand{\indexname}{Index}
-%end{latexonly}
-\input{lib.ind} % Index
-
-\end{document}
diff --git a/Doc/lib/libaifc.tex b/Doc/lib/libaifc.tex
deleted file mode 100644
index 65abe84844..0000000000
--- a/Doc/lib/libaifc.tex
+++ /dev/null
@@ -1,202 +0,0 @@
-\section{\module{aifc} ---
- Read and write AIFF and AIFC files}
-
-\declaremodule{standard}{aifc}
-\modulesynopsis{Read and write audio files in AIFF or AIFC format.}
-
-
-This module provides support for reading and writing AIFF and AIFF-C
-files. AIFF is Audio Interchange File Format, a format for storing
-digital audio samples in a file. AIFF-C is a newer version of the
-format that includes the ability to compress the audio data.
-\index{Audio Interchange File Format}
-\index{AIFF}
-\index{AIFF-C}
-
-\strong{Caveat:} Some operations may only work under IRIX; these will
-raise \exception{ImportError} when attempting to import the
-\module{cl} module, which is only available on IRIX.
-
-Audio files have a number of parameters that describe the audio data.
-The sampling rate or frame rate is the number of times per second the
-sound is sampled. The number of channels indicate if the audio is
-mono, stereo, or quadro. Each frame consists of one sample per
-channel. The sample size is the size in bytes of each sample. Thus a
-frame consists of \var{nchannels}*\var{samplesize} bytes, and a
-second's worth of audio consists of
-\var{nchannels}*\var{samplesize}*\var{framerate} bytes.
-
-For example, CD quality audio has a sample size of two bytes (16
-bits), uses two channels (stereo) and has a frame rate of 44,100
-frames/second. This gives a frame size of 4 bytes (2*2), and a
-second's worth occupies 2*2*44100 bytes (176,400 bytes).
-
-Module \module{aifc} defines the following function:
-
-\begin{funcdesc}{open}{file\optional{, mode}}
-Open an AIFF or AIFF-C file and return an object instance with
-methods that are described below. The argument \var{file} is either a
-string naming a file or a file object. \var{mode} must be \code{'r'}
-or \code{'rb'} when the file must be opened for reading, or \code{'w'}
-or \code{'wb'} when the file must be opened for writing. If omitted,
-\code{\var{file}.mode} is used if it exists, otherwise \code{'rb'} is
-used. When used for writing, the file object should be seekable,
-unless you know ahead of time how many samples you are going to write
-in total and use \method{writeframesraw()} and \method{setnframes()}.
-\end{funcdesc}
-
-Objects returned by \function{open()} when a file is opened for
-reading have the following methods:
-
-\begin{methoddesc}[aifc]{getnchannels}{}
-Return the number of audio channels (1 for mono, 2 for stereo).
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{getsampwidth}{}
-Return the size in bytes of individual samples.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{getframerate}{}
-Return the sampling rate (number of audio frames per second).
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{getnframes}{}
-Return the number of audio frames in the file.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{getcomptype}{}
-Return a four-character string describing the type of compression used
-in the audio file. For AIFF files, the returned value is
-\code{'NONE'}.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{getcompname}{}
-Return a human-readable description of the type of compression used in
-the audio file. For AIFF files, the returned value is \code{'not
-compressed'}.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{getparams}{}
-Return a tuple consisting of all of the above values in the above
-order.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{getmarkers}{}
-Return a list of markers in the audio file. A marker consists of a
-tuple of three elements. The first is the mark ID (an integer), the
-second is the mark position in frames from the beginning of the data
-(an integer), the third is the name of the mark (a string).
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{getmark}{id}
-Return the tuple as described in \method{getmarkers()} for the mark
-with the given \var{id}.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{readframes}{nframes}
-Read and return the next \var{nframes} frames from the audio file. The
-returned data is a string containing for each frame the uncompressed
-samples of all channels.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{rewind}{}
-Rewind the read pointer. The next \method{readframes()} will start from
-the beginning.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{setpos}{pos}
-Seek to the specified frame number.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{tell}{}
-Return the current frame number.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{close}{}
-Close the AIFF file. After calling this method, the object can no
-longer be used.
-\end{methoddesc}
-
-Objects returned by \function{open()} when a file is opened for
-writing have all the above methods, except for \method{readframes()} and
-\method{setpos()}. In addition the following methods exist. The
-\method{get*()} methods can only be called after the corresponding
-\method{set*()} methods have been called. Before the first
-\method{writeframes()} or \method{writeframesraw()}, all parameters
-except for the number of frames must be filled in.
-
-\begin{methoddesc}[aifc]{aiff}{}
-Create an AIFF file. The default is that an AIFF-C file is created,
-unless the name of the file ends in \code{'.aiff'} in which case the
-default is an AIFF file.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{aifc}{}
-Create an AIFF-C file. The default is that an AIFF-C file is created,
-unless the name of the file ends in \code{'.aiff'} in which case the
-default is an AIFF file.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{setnchannels}{nchannels}
-Specify the number of channels in the audio file.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{setsampwidth}{width}
-Specify the size in bytes of audio samples.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{setframerate}{rate}
-Specify the sampling frequency in frames per second.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{setnframes}{nframes}
-Specify the number of frames that are to be written to the audio file.
-If this parameter is not set, or not set correctly, the file needs to
-support seeking.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{setcomptype}{type, name}
-Specify the compression type. If not specified, the audio data will
-not be compressed. In AIFF files, compression is not possible. The
-name parameter should be a human-readable description of the
-compression type, the type parameter should be a four-character
-string. Currently the following compression types are supported:
-NONE, ULAW, ALAW, G722.
-\index{u-LAW}
-\index{A-LAW}
-\index{G.722}
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{setparams}{nchannels, sampwidth, framerate, comptype, compname}
-Set all the above parameters at once. The argument is a tuple
-consisting of the various parameters. This means that it is possible
-to use the result of a \method{getparams()} call as argument to
-\method{setparams()}.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{setmark}{id, pos, name}
-Add a mark with the given id (larger than 0), and the given name at
-the given position. This method can be called at any time before
-\method{close()}.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{tell}{}
-Return the current write position in the output file. Useful in
-combination with \method{setmark()}.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{writeframes}{data}
-Write data to the output file. This method can only be called after
-the audio file parameters have been set.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{writeframesraw}{data}
-Like \method{writeframes()}, except that the header of the audio file
-is not updated.
-\end{methoddesc}
-
-\begin{methoddesc}[aifc]{close}{}
-Close the AIFF file. The header of the file is updated to reflect the
-actual size of the audio data. After calling this method, the object
-can no longer be used.
-\end{methoddesc}
diff --git a/Doc/lib/libal.tex b/Doc/lib/libal.tex
deleted file mode 100644
index 7159d6fb69..0000000000
--- a/Doc/lib/libal.tex
+++ /dev/null
@@ -1,181 +0,0 @@
-\section{\module{al} ---
- Audio functions on the SGI}
-
-\declaremodule{builtin}{al}
- \platform{IRIX}
-\modulesynopsis{Audio functions on the SGI.}
-
-
-This module provides access to the audio facilities of the SGI Indy
-and Indigo workstations. See section 3A of the IRIX man pages for
-details. You'll need to read those man pages to understand what these
-functions do! Some of the functions are not available in IRIX
-releases before 4.0.5. Again, see the manual to check whether a
-specific function is available on your platform.
-
-All functions and methods defined in this module are equivalent to
-the C functions with \samp{AL} prefixed to their name.
-
-Symbolic constants from the C header file \code{} are
-defined in the standard module
-\refmodule[al-constants]{AL}\refstmodindex{AL}, see below.
-
-\warning{The current version of the audio library may dump core
-when bad argument values are passed rather than returning an error
-status. Unfortunately, since the precise circumstances under which
-this may happen are undocumented and hard to check, the Python
-interface can provide no protection against this kind of problems.
-(One example is specifying an excessive queue size --- there is no
-documented upper limit.)}
-
-The module defines the following functions:
-
-
-\begin{funcdesc}{openport}{name, direction\optional{, config}}
-The name and direction arguments are strings. The optional
-\var{config} argument is a configuration object as returned by
-\function{newconfig()}. The return value is an \dfn{audio port
-object}; methods of audio port objects are described below.
-\end{funcdesc}
-
-\begin{funcdesc}{newconfig}{}
-The return value is a new \dfn{audio configuration object}; methods of
-audio configuration objects are described below.
-\end{funcdesc}
-
-\begin{funcdesc}{queryparams}{device}
-The device argument is an integer. The return value is a list of
-integers containing the data returned by \cfunction{ALqueryparams()}.
-\end{funcdesc}
-
-\begin{funcdesc}{getparams}{device, list}
-The \var{device} argument is an integer. The list argument is a list
-such as returned by \function{queryparams()}; it is modified in place
-(!).
-\end{funcdesc}
-
-\begin{funcdesc}{setparams}{device, list}
-The \var{device} argument is an integer. The \var{list} argument is a
-list such as returned by \function{queryparams()}.
-\end{funcdesc}
-
-
-\subsection{Configuration Objects \label{al-config-objects}}
-
-Configuration objects (returned by \function{newconfig()} have the
-following methods:
-
-\begin{methoddesc}[audio configuration]{getqueuesize}{}
-Return the queue size.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{setqueuesize}{size}
-Set the queue size.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{getwidth}{}
-Get the sample width.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{setwidth}{width}
-Set the sample width.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{getchannels}{}
-Get the channel count.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{setchannels}{nchannels}
-Set the channel count.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{getsampfmt}{}
-Get the sample format.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{setsampfmt}{sampfmt}
-Set the sample format.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{getfloatmax}{}
-Get the maximum value for floating sample formats.
-\end{methoddesc}
-
-\begin{methoddesc}[audio configuration]{setfloatmax}{floatmax}
-Set the maximum value for floating sample formats.
-\end{methoddesc}
-
-
-\subsection{Port Objects \label{al-port-objects}}
-
-Port objects, as returned by \function{openport()}, have the following
-methods:
-
-\begin{methoddesc}[audio port]{closeport}{}
-Close the port.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{getfd}{}
-Return the file descriptor as an int.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{getfilled}{}
-Return the number of filled samples.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{getfillable}{}
-Return the number of fillable samples.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{readsamps}{nsamples}
-Read a number of samples from the queue, blocking if necessary.
-Return the data as a string containing the raw data, (e.g., 2 bytes per
-sample in big-endian byte order (high byte, low byte) if you have set
-the sample width to 2 bytes).
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{writesamps}{samples}
-Write samples into the queue, blocking if necessary. The samples are
-encoded as described for the \method{readsamps()} return value.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{getfillpoint}{}
-Return the `fill point'.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{setfillpoint}{fillpoint}
-Set the `fill point'.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{getconfig}{}
-Return a configuration object containing the current configuration of
-the port.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{setconfig}{config}
-Set the configuration from the argument, a configuration object.
-\end{methoddesc}
-
-\begin{methoddesc}[audio port]{getstatus}{list}
-Get status information on last error.
-\end{methoddesc}
-
-
-\section{\module{AL} ---
- Constants used with the \module{al} module}
-
-\declaremodule[al-constants]{standard}{AL}
- \platform{IRIX}
-\modulesynopsis{Constants used with the \module{al} module.}
-
-
-This module defines symbolic constants needed to use the built-in
-module \refmodule{al} (see above); they are equivalent to those defined
-in the C header file \code{} except that the name prefix
-\samp{AL_} is omitted. Read the module source for a complete list of
-the defined names. Suggested use:
-
-\begin{verbatim}
-import al
-from AL import *
-\end{verbatim}
diff --git a/Doc/lib/liballos.tex b/Doc/lib/liballos.tex
deleted file mode 100644
index dd046c95bc..0000000000
--- a/Doc/lib/liballos.tex
+++ /dev/null
@@ -1,9 +0,0 @@
-\chapter{Generic Operating System Services \label{allos}}
-
-The modules described in this chapter provide interfaces to operating
-system features that are available on (almost) all operating systems,
-such as files and a clock. The interfaces are generally modeled
-after the \UNIX{} or C interfaces, but they are available on most
-other systems as well. Here's an overview:
-
-\localmoduletable
diff --git a/Doc/lib/libamoeba.tex b/Doc/lib/libamoeba.tex
deleted file mode 100644
index c3274db069..0000000000
--- a/Doc/lib/libamoeba.tex
+++ /dev/null
@@ -1,132 +0,0 @@
-\chapter{Amoeba Specific Services}
-
-\section{\module{amoeba} ---
- Amoeba system support}
-
-\declaremodule{builtin}{amoeba}
- \platform{Amoeba}
-\modulesynopsis{Functions for the Amoeba operating system.}
-
-
-This module provides some object types and operations useful for
-Amoeba applications. It is only available on systems that support
-Amoeba operations. RPC errors and other Amoeba errors are reported as
-the exception \code{amoeba.error = 'amoeba.error'}.
-
-The module \module{amoeba} defines the following items:
-
-\begin{funcdesc}{name_append}{path, cap}
-Stores a capability in the Amoeba directory tree.
-Arguments are the pathname (a string) and the capability (a capability
-object as returned by
-\function{name_lookup()}).
-\end{funcdesc}
-
-\begin{funcdesc}{name_delete}{path}
-Deletes a capability from the Amoeba directory tree.
-Argument is the pathname.
-\end{funcdesc}
-
-\begin{funcdesc}{name_lookup}{path}
-Looks up a capability.
-Argument is the pathname.
-Returns a
-\dfn{capability}
-object, to which various interesting operations apply, described below.
-\end{funcdesc}
-
-\begin{funcdesc}{name_replace}{path, cap}
-Replaces a capability in the Amoeba directory tree.
-Arguments are the pathname and the new capability.
-(This differs from
-\function{name_append()}
-in the behavior when the pathname already exists:
-\function{name_append()}
-finds this an error while
-\function{name_replace()}
-allows it, as its name suggests.)
-\end{funcdesc}
-
-\begin{datadesc}{capv}
-A table representing the capability environment at the time the
-interpreter was started.
-(Alas, modifying this table does not affect the capability environment
-of the interpreter.)
-For example,
-\code{amoeba.capv['ROOT']}
-is the capability of your root directory, similar to
-\code{getcap("ROOT")}
-in C.
-\end{datadesc}
-
-\begin{excdesc}{error}
-The exception raised when an Amoeba function returns an error.
-The value accompanying this exception is a pair containing the numeric
-error code and the corresponding string, as returned by the C function
-\cfunction{err_why()}.
-\end{excdesc}
-
-\begin{funcdesc}{timeout}{msecs}
-Sets the transaction timeout, in milliseconds.
-Returns the previous timeout.
-Initially, the timeout is set to 2 seconds by the Python interpreter.
-\end{funcdesc}
-
-\subsection{Capability Operations}
-
-Capabilities are written in a convenient \ASCII{} format, also used by the
-Amoeba utilities
-\emph{c2a}(U)
-and
-\emph{a2c}(U).
-For example:
-
-\begin{verbatim}
->>> amoeba.name_lookup('/profile/cap')
-aa:1c:95:52:6a:fa/14(ff)/8e:ba:5b:8:11:1a
->>>
-\end{verbatim}
-%
-The following methods are defined for capability objects.
-
-\setindexsubitem{(capability method)}
-\begin{funcdesc}{dir_list}{}
-Returns a list of the names of the entries in an Amoeba directory.
-\end{funcdesc}
-
-\begin{funcdesc}{b_read}{offset, maxsize}
-Reads (at most)
-\var{maxsize}
-bytes from a bullet file at offset
-\var{offset.}
-The data is returned as a string.
-EOF is reported as an empty string.
-\end{funcdesc}
-
-\begin{funcdesc}{b_size}{}
-Returns the size of a bullet file.
-\end{funcdesc}
-
-\begin{funcdesc}{dir_append}{}
-\funcline{dir_delete}{}
-\funcline{dir_lookup}{}
-\funcline{dir_replace}{}
-Like the corresponding
-\samp{name_}*
-functions, but with a path relative to the capability.
-(For paths beginning with a slash the capability is ignored, since this
-is the defined semantics for Amoeba.)
-\end{funcdesc}
-
-\begin{funcdesc}{std_info}{}
-Returns the standard info string of the object.
-\end{funcdesc}
-
-\begin{funcdesc}{tod_gettime}{}
-Returns the time (in seconds since the Epoch, in UCT, as for \POSIX) from
-a time server.
-\end{funcdesc}
-
-\begin{funcdesc}{tod_settime}{t}
-Sets the time kept by a time server.
-\end{funcdesc}
diff --git a/Doc/lib/libanydbm.tex b/Doc/lib/libanydbm.tex
deleted file mode 100644
index eef4d03e24..0000000000
--- a/Doc/lib/libanydbm.tex
+++ /dev/null
@@ -1,96 +0,0 @@
-\section{\module{anydbm} ---
- Generic access to DBM-style databases}
-
-\declaremodule{standard}{anydbm}
-\modulesynopsis{Generic interface to DBM-style database modules.}
-
-
-\module{anydbm} is a generic interface to variants of the DBM
-database --- \refmodule{dbhash}\refstmodindex{dbhash} (requires
-\refmodule{bsddb}\refbimodindex{bsddb}),
-\refmodule{gdbm}\refbimodindex{gdbm}, or
-\refmodule{dbm}\refbimodindex{dbm}. If none of these modules is
-installed, the slow-but-simple implementation in module
-\refmodule{dumbdbm}\refstmodindex{dumbdbm} will be used.
-
-\begin{funcdesc}{open}{filename\optional{, flag\optional{, mode}}}
-Open the database file \var{filename} and return a corresponding object.
-
-If the database file already exists, the \refmodule{whichdb} module is
-used to determine its type and the appropriate module is used; if it
-does not exist, the first module listed above that can be imported is
-used.
-
-The optional \var{flag} argument can be
-\code{'r'} to open an existing database for reading only,
-\code{'w'} to open an existing database for reading and writing,
-\code{'c'} to create the database if it doesn't exist, or
-\code{'n'}, which will always create a new empty database. If not
-specified, the default value is \code{'r'}.
-
-The optional \var{mode} argument is the \UNIX{} mode of the file, used
-only when the database has to be created. It defaults to octal
-\code{0666} (and will be modified by the prevailing umask).
-\end{funcdesc}
-
-\begin{excdesc}{error}
-A tuple containing the exceptions that can be raised by each of the
-supported modules, with a unique exception \exception{anydbm.error} as
-the first item --- the latter is used when \exception{anydbm.error} is
-raised.
-\end{excdesc}
-
-The object returned by \function{open()} supports most of the same
-functionality as dictionaries; keys and their corresponding values can
-be stored, retrieved, and deleted, and the \method{has_key()} and
-\method{keys()} methods are available. Keys and values must always be
-strings.
-
-
-\begin{seealso}
- \seemodule{dbhash}{BSD \code{db} database interface.}
- \seemodule{dbm}{Standard \UNIX{} database interface.}
- \seemodule{dumbdbm}{Portable implementation of the \code{dbm} interface.}
- \seemodule{gdbm}{GNU database interface, based on the \code{dbm} interface.}
- \seemodule{shelve}{General object persistence built on top of
- the Python \code{dbm} interface.}
- \seemodule{whichdb}{Utility module used to determine the type of an
- existing database.}
-\end{seealso}
-
-
-\section{\module{dumbdbm} ---
- Portable DBM implementation}
-
-\declaremodule{standard}{dumbdbm}
-\modulesynopsis{Portable implementation of the simple DBM interface.}
-
-
-A simple and slow database implemented entirely in Python. This
-should only be used when no other DBM-style database is available.
-
-
-\begin{funcdesc}{open}{filename\optional{, flag\optional{, mode}}}
-Open the database file \var{filename} and return a corresponding
-object. The \var{flag} argument, used to control how the database is
-opened in the other DBM implementations, is ignored in
-\module{dumbdbm}; the database is always opened for update, and will
-be created if it does not exist.
-
-The optional \var{mode} argument is the \UNIX{} mode of the file, used
-only when the database has to be created. It defaults to octal
-\code{0666} (and will be modified by the prevailing umask).
-\versionchanged[The \var{mode} argument was ignored in earlier
- versions]{2.2}
-\end{funcdesc}
-
-\begin{excdesc}{error}
-Raised for errors not reported as \exception{KeyError} errors.
-\end{excdesc}
-
-
-\begin{seealso}
- \seemodule{anydbm}{Generic interface to \code{dbm}-style databases.}
- \seemodule{whichdb}{Utility module used to determine the type of an
- existing database.}
-\end{seealso}
diff --git a/Doc/lib/libarray.tex b/Doc/lib/libarray.tex
deleted file mode 100644
index 6ec056fbf2..0000000000
--- a/Doc/lib/libarray.tex
+++ /dev/null
@@ -1,234 +0,0 @@
-\section{\module{array} ---
- Efficient arrays of numeric values}
-
-\declaremodule{builtin}{array}
-\modulesynopsis{Efficient arrays of uniformly typed numeric values.}
-
-
-This module defines an object type which can efficiently represent
-an array of basic values: characters, integers, floating point
-numbers. Arrays\index{arrays} are sequence types and behave very much
-like lists, except that the type of objects stored in them is
-constrained. The type is specified at object creation time by using a
-\dfn{type code}, which is a single character. The following type
-codes are defined:
-
-\begin{tableiv}{c|l|l|c}{code}{Type code}{C Type}{Python Type}{Minimum size in bytes}
- \lineiv{'c'}{char} {character} {1}
- \lineiv{'b'}{signed char} {int} {1}
- \lineiv{'B'}{unsigned char} {int} {1}
- \lineiv{'u'}{Py_UNICODE} {Unicode character}{2}
- \lineiv{'h'}{signed short} {int} {2}
- \lineiv{'H'}{unsigned short}{int} {2}
- \lineiv{'i'}{signed int} {int} {2}
- \lineiv{'I'}{unsigned int} {long} {2}
- \lineiv{'l'}{signed long} {int} {4}
- \lineiv{'L'}{unsigned long} {long} {4}
- \lineiv{'f'}{float} {float} {4}
- \lineiv{'d'}{double} {float} {8}
-\end{tableiv}
-
-The actual representation of values is determined by the machine
-architecture (strictly speaking, by the C implementation). The actual
-size can be accessed through the \member{itemsize} attribute. The values
-stored for \code{'L'} and \code{'I'} items will be represented as
-Python long integers when retrieved, because Python's plain integer
-type cannot represent the full range of C's unsigned (long) integers.
-
-
-The module defines the following type:
-
-\begin{funcdesc}{array}{typecode\optional{, initializer}}
-Return a new array whose items are restricted by \var{typecode},
-and initialized from the optional \var{initializer} value, which
-must be a list or a string. The list or string is passed to the
-new array's \method{fromlist()}, \method{fromstring()}, or
-\method{fromunicode()} method (see below) to add initial items to
-the array.
-\end{funcdesc}
-
-\begin{datadesc}{ArrayType}
-Obsolete alias for \function{array}.
-\end{datadesc}
-
-
-Array objects support the ordinary sequence operations of
-indexing, slicing, concatenation, and multiplication. When using
-slice assignment, the assigned value must be an array object with the
-same type code; in all other cases, \exception{TypeError} is raised.
-Array objects also implement the buffer interface, and may be used
-wherever buffer objects are supported.
-
-The following data items and methods are also supported:
-
-\begin{memberdesc}[array]{typecode}
-The typecode character used to create the array.
-\end{memberdesc}
-
-\begin{memberdesc}[array]{itemsize}
-The length in bytes of one array item in the internal representation.
-\end{memberdesc}
-
-
-\begin{methoddesc}[array]{append}{x}
-Append a new item with value \var{x} to the end of the array.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{buffer_info}{}
-Return a tuple \code{(\var{address}, \var{length})} giving the current
-memory address and the length in elements of the buffer used to hold
-array's contents. The size of the memory buffer in bytes can be
-computed as \code{\var{array}.buffer_info()[1] *
-\var{array}.itemsize}. This is occasionally useful when working with
-low-level (and inherently unsafe) I/O interfaces that require memory
-addresses, such as certain \cfunction{ioctl()} operations. The
-returned numbers are valid as long as the array exists and no
-length-changing operations are applied to it.
-
-\note{When using array objects from code written in C or
-\Cpp{} (the only way to effectively make use of this information), it
-makes more sense to use the buffer interface supported by array
-objects. This method is maintained for backward compatibility and
-should be avoided in new code. The buffer interface is documented in
-the \citetitle[../api/newTypes.html]{Python/C API Reference Manual}.}
-\end{methoddesc}
-
-\begin{methoddesc}[array]{byteswap}{}
-``Byteswap'' all items of the array. This is only supported for
-values which are 1, 2, 4, or 8 bytes in size; for other types of
-values, \exception{RuntimeError} is raised. It is useful when reading
-data from a file written on a machine with a different byte order.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{count}{x}
-Return the number of occurences of \var{x} in the array.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{extend}{a}
-Append array items from \var{a} to the end of the array. The two
-arrays must have \emph{exactly} the same type code; if not,
-\exception{TypeError} will be raised.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{fromfile}{f, n}
-Read \var{n} items (as machine values) from the file object \var{f}
-and append them to the end of the array. If less than \var{n} items
-are available, \exception{EOFError} is raised, but the items that were
-available are still inserted into the array. \var{f} must be a real
-built-in file object; something else with a \method{read()} method won't
-do.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{fromlist}{list}
-Append items from the list. This is equivalent to
-\samp{for x in \var{list}:\ a.append(x)}
-except that if there is a type error, the array is unchanged.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{fromstring}{s}
-Appends items from the string, interpreting the string as an
-array of machine values (as if it had been read from a
-file using the \method{fromfile()} method).
-\end{methoddesc}
-
-\begin{methoddesc}[array]{fromunicode}{s}
-Extends this array with data from the given unicode string.
-The array must be a type 'u' array; otherwise a ValueError
-is raised. Use \samp{array.fromstring(ustr.decode(enc))} to
-append Unicode data to an array of some other type.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{index}{x}
-Return the smallest \var{i} such that \var{i} is the index of
-the first occurence of \var{x} in the array.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{insert}{i, x}
-Insert a new item with value \var{x} in the array before position
-\var{i}. Negative values are treated as being relative to the end
-of the array.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{pop}{\optional{i}}
-Removes the item with the index \var{i} from the array and returns
-it. The optional argument defaults to \code{-1}, so that by default
-the last item is removed and returned.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{read}{f, n}
-\deprecated {1.5.1}
- {Use the \method{fromfile()} method.}
-Read \var{n} items (as machine values) from the file object \var{f}
-and append them to the end of the array. If less than \var{n} items
-are available, \exception{EOFError} is raised, but the items that were
-available are still inserted into the array. \var{f} must be a real
-built-in file object; something else with a \method{read()} method won't
-do.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{remove}{x}
-Remove the first occurence of \var{x} from the array.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{reverse}{}
-Reverse the order of the items in the array.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{tofile}{f}
-Write all items (as machine values) to the file object \var{f}.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{tolist}{}
-Convert the array to an ordinary list with the same items.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{tostring}{}
-Convert the array to an array of machine values and return the
-string representation (the same sequence of bytes that would
-be written to a file by the \method{tofile()} method.)
-\end{methoddesc}
-
-\begin{methoddesc}[array]{tounicode}{}
-Convert the array to a unicode string. The array must be
-a type 'u' array; otherwise a ValueError is raised. Use
-array.tostring().decode(enc) to obtain a unicode string
-from an array of some other type.
-\end{methoddesc}
-
-\begin{methoddesc}[array]{write}{f}
-\deprecated {1.5.1}
- {Use the \method{tofile()} method.}
-Write all items (as machine values) to the file object \var{f}.
-\end{methoddesc}
-
-When an array object is printed or converted to a string, it is
-represented as \code{array(\var{typecode}, \var{initializer})}. The
-\var{initializer} is omitted if the array is empty, otherwise it is a
-string if the \var{typecode} is \code{'c'}, otherwise it is a list of
-numbers. The string is guaranteed to be able to be converted back to
-an array with the same type and value using reverse quotes
-(\code{``}), so long as the \function{array()} function has been
-imported using \code{from array import array}. Examples:
-
-\begin{verbatim}
-array('l')
-array('c', 'hello world')
-array('u', u'hello \textbackslash u2641')
-array('l', [1, 2, 3, 4, 5])
-array('d', [1.0, 2.0, 3.14])
-\end{verbatim}
-
-
-\begin{seealso}
- \seemodule{struct}{Packing and unpacking of heterogeneous binary data.}
- \seemodule{xdrlib}{Packing and unpacking of External Data
- Representation (XDR) data as used in some remote
- procedure call systems.}
- \seetitle[http://numpy.sourceforge.net/numdoc/HTML/numdoc.htm]{The
- Numerical Python Manual}{The Numeric Python extension
- (NumPy) defines another array type; see
- \url{http://numpy.sourceforge.net/} for further information
- about Numerical Python. (A PDF version of the NumPy manual
- is available at
- \url{http://numpy.sourceforge.net/numdoc/numdoc.pdf}).}
-\end{seealso}
diff --git a/Doc/lib/libascii.tex b/Doc/lib/libascii.tex
deleted file mode 100644
index 003bd9544d..0000000000
--- a/Doc/lib/libascii.tex
+++ /dev/null
@@ -1,175 +0,0 @@
-\section{\module{curses.ascii} ---
- Utilities for ASCII characters}
-
-\declaremodule{standard}{curses.ascii}
-\modulesynopsis{Constants and set-membership functions for
- \ASCII\ characters.}
-\moduleauthor{Eric S. Raymond}{esr@thyrsus.com}
-\sectionauthor{Eric S. Raymond}{esr@thyrsus.com}
-
-\versionadded{1.6}
-
-The \module{curses.ascii} module supplies name constants for
-\ASCII{} characters and functions to test membership in various
-\ASCII{} character classes. The constants supplied are names for
-control characters as follows:
-
-\begin{tableii}{l|l}{constant}{Name}{Meaning}
- \lineii{NUL}{}
- \lineii{SOH}{Start of heading, console interrupt}
- \lineii{STX}{Start of text}
- \lineii{ETX}{End of text}
- \lineii{EOT}{End of transmission}
- \lineii{ENQ}{Enquiry, goes with \constant{ACK} flow control}
- \lineii{ACK}{Acknowledgement}
- \lineii{BEL}{Bell}
- \lineii{BS}{Backspace}
- \lineii{TAB}{Tab}
- \lineii{HT}{Alias for \constant{TAB}: ``Horizontal tab''}
- \lineii{LF}{Line feed}
- \lineii{NL}{Alias for \constant{LF}: ``New line''}
- \lineii{VT}{Vertical tab}
- \lineii{FF}{Form feed}
- \lineii{CR}{Carriage return}
- \lineii{SO}{Shift-out, begin alternate character set}
- \lineii{SI}{Shift-in, resume default character set}
- \lineii{DLE}{Data-link escape}
- \lineii{DC1}{XON, for flow control}
- \lineii{DC2}{Device control 2, block-mode flow control}
- \lineii{DC3}{XOFF, for flow control}
- \lineii{DC4}{Device control 4}
- \lineii{NAK}{Negative acknowledgement}
- \lineii{SYN}{Synchronous idle}
- \lineii{ETB}{End transmission block}
- \lineii{CAN}{Cancel}
- \lineii{EM}{End of medium}
- \lineii{SUB}{Substitute}
- \lineii{ESC}{Escape}
- \lineii{FS}{File separator}
- \lineii{GS}{Group separator}
- \lineii{RS}{Record separator, block-mode terminator}
- \lineii{US}{Unit separator}
- \lineii{SP}{Space}
- \lineii{DEL}{Delete}
-\end{tableii}
-
-Note that many of these have little practical significance in modern
-usage. The mnemonics derive from teleprinter conventions that predate
-digital computers.
-
-The module supplies the following functions, patterned on those in the
-standard C library:
-
-
-\begin{funcdesc}{isalnum}{c}
-Checks for an \ASCII{} alphanumeric character; it is equivalent to
-\samp{isalpha(\var{c}) or isdigit(\var{c})}.
-\end{funcdesc}
-
-\begin{funcdesc}{isalpha}{c}
-Checks for an \ASCII{} alphabetic character; it is equivalent to
-\samp{isupper(\var{c}) or islower(\var{c})}.
-\end{funcdesc}
-
-\begin{funcdesc}{isascii}{c}
-Checks for a character value that fits in the 7-bit \ASCII{} set.
-\end{funcdesc}
-
-\begin{funcdesc}{isblank}{c}
-Checks for an \ASCII{} whitespace character.
-\end{funcdesc}
-
-\begin{funcdesc}{iscntrl}{c}
-Checks for an \ASCII{} control character (in the range 0x00 to 0x1f).
-\end{funcdesc}
-
-\begin{funcdesc}{isdigit}{c}
-Checks for an \ASCII{} decimal digit, \character{0} through
-\character{9}. This is equivalent to \samp{\var{c} in string.digits}.
-\end{funcdesc}
-
-\begin{funcdesc}{isgraph}{c}
-Checks for \ASCII{} any printable character except space.
-\end{funcdesc}
-
-\begin{funcdesc}{islower}{c}
-Checks for an \ASCII{} lower-case character.
-\end{funcdesc}
-
-\begin{funcdesc}{isprint}{c}
-Checks for any \ASCII{} printable character including space.
-\end{funcdesc}
-
-\begin{funcdesc}{ispunct}{c}
-Checks for any printable \ASCII{} character which is not a space or an
-alphanumeric character.
-\end{funcdesc}
-
-\begin{funcdesc}{isspace}{c}
-Checks for \ASCII{} white-space characters; space, line feed,
-carriage return, form feed, horizontal tab, vertical tab.
-\end{funcdesc}
-
-\begin{funcdesc}{isupper}{c}
-Checks for an \ASCII{} uppercase letter.
-\end{funcdesc}
-
-\begin{funcdesc}{isxdigit}{c}
-Checks for an \ASCII{} hexadecimal digit. This is equivalent to
-\samp{\var{c} in string.hexdigits}.
-\end{funcdesc}
-
-\begin{funcdesc}{isctrl}{c}
-Checks for an \ASCII{} control character (ordinal values 0 to 31).
-\end{funcdesc}
-
-\begin{funcdesc}{ismeta}{c}
-Checks for a non-\ASCII{} character (ordinal values 0x80 and above).
-\end{funcdesc}
-
-These functions accept either integers or strings; when the argument
-is a string, it is first converted using the built-in function
-\function{ord()}.
-
-Note that all these functions check ordinal bit values derived from the
-first character of the string you pass in; they do not actually know
-anything about the host machine's character encoding. For functions
-that know about the character encoding (and handle
-internationalization properly) see the \refmodule{string} module.
-
-The following two functions take either a single-character string or
-integer byte value; they return a value of the same type.
-
-\begin{funcdesc}{ascii}{c}
-Return the ASCII value corresponding to the low 7 bits of \var{c}.
-\end{funcdesc}
-
-\begin{funcdesc}{ctrl}{c}
-Return the control character corresponding to the given character
-(the character bit value is bitwise-anded with 0x1f).
-\end{funcdesc}
-
-\begin{funcdesc}{alt}{c}
-Return the 8-bit character corresponding to the given ASCII character
-(the character bit value is bitwise-ored with 0x80).
-\end{funcdesc}
-
-The following function takes either a single-character string or
-integer value; it returns a string.
-
-\begin{funcdesc}{unctrl}{c}
-Return a string representation of the \ASCII{} character \var{c}. If
-\var{c} is printable, this string is the character itself. If the
-character is a control character (0x00-0x1f) the string consists of a
-caret (\character{\^}) followed by the corresponding uppercase letter.
-If the character is an \ASCII{} delete (0x7f) the string is
-\code{'\^{}?'}. If the character has its meta bit (0x80) set, the meta
-bit is stripped, the preceding rules applied, and
-\character{!} prepended to the result.
-\end{funcdesc}
-
-\begin{datadesc}{controlnames}
-A 33-element string array that contains the \ASCII{} mnemonics for the
-thirty-two \ASCII{} control characters from 0 (NUL) to 0x1f (US), in
-order, plus the mnemonic \samp{SP} for the space character.
-\end{datadesc}
diff --git a/Doc/lib/libasynchat.tex b/Doc/lib/libasynchat.tex
deleted file mode 100644
index 223bfed746..0000000000
--- a/Doc/lib/libasynchat.tex
+++ /dev/null
@@ -1,254 +0,0 @@
-\section{\module{asynchat} ---
- Asynchronous socket command/response handler}
-
-\declaremodule{standard}{asynchat}
-\modulesynopsis{Support for asynchronous command/response protocols.}
-\moduleauthor{Sam Rushing}{rushing@nightmare.com}
-\sectionauthor{Steve Holden}{sholden@holdenweb.com}
-
-This module builds on the \refmodule{asyncore} infrastructure,
-simplifying asynchronous clients and servers and making it easier to
-handle protocols whose elements are terminated by arbitrary strings, or
-are of variable length. \refmodule{asynchat} defines the abstract class
-\class{async_chat} that you subclass, providing implementations of the
-\method{collect_incoming_data()} and \method{found_terminator()}
-methods. It uses the same asynchronous loop as \refmodule{asyncore}, and
-the two types of channel, \class{asyncore.dispatcher} and
-\class{asynchat.async_chat}, can freely be mixed in the channel map.
-Typically an \class{asyncore.dispatcher} server channel generates new
-\class{asynchat.async_chat} channel objects as it receives incoming
-connection requests.
-
-\begin{classdesc}{async_chat}{}
- This class is an abstract subclass of \class{asyncore.dispatcher}. To make
- practical use of the code you must subclass \class{async_chat}, providing
- meaningful \method{collect_incoming_data()} and \method{found_terminator()}
- methods. The \class{asyncore.dispatcher} methods can be
- used, although not all make sense in a message/response context.
-
- Like \class{asyncore.dispatcher}, \class{async_chat} defines a set of events
- that are generated by an analysis of socket conditions after a
- \cfunction{select()} call. Once the polling loop has been started the
- \class{async_chat} object's methods are called by the event-processing
- framework with no action on the part of the programmer.
-
- Unlike \class{asyncore.dispatcher}, \class{async_chat} allows you to define
- a first-in-first-out queue (fifo) of \emph{producers}. A producer need have
- only one method, \method{more()}, which should return data to be transmitted
- on the channel. The producer indicates exhaustion (\emph{i.e.} that it contains
- no more data) by having its \method{more()} method return the empty string. At
- this point the \class{async_chat} object removes the producer from the fifo
- and starts using the next producer, if any. When the producer fifo is empty
- the \method{handle_write()} method does nothing. You use the channel object's
- \method{set_terminator()} method to describe how to recognize the end
- of, or an important breakpoint in, an incoming transmission from the
- remote endpoint.
-
- To build a functioning \class{async_chat} subclass your
- input methods \method{collect_incoming_data()} and
- \method{found_terminator()} must handle the data that the channel receives
- asynchronously. The methods are described below.
-\end{classdesc}
-
-\begin{methoddesc}{close_when_done}{}
- Pushes a \code{None} on to the producer fifo. When this producer is
- popped off the fifo it causes the channel to be closed.
-\end{methoddesc}
-
-\begin{methoddesc}{collect_incoming_data}{data}
- Called with \var{data} holding an arbitrary amount of received data.
- The default method, which must be overridden, raises a \exception{NotImplementedError} exception.
-\end{methoddesc}
-
-\begin{methoddesc}{discard_buffers}{}
- In emergencies this method will discard any data held in the input and/or
- output buffers and the producer fifo.
-\end{methoddesc}
-
-\begin{methoddesc}{found_terminator}{}
- Called when the incoming data stream matches the termination condition
- set by \method{set_terminator}. The default method, which must be overridden,
- raises a \exception{NotImplementedError} exception. The buffered input data should
- be available via an instance attribute.
-\end{methoddesc}
-
-\begin{methoddesc}{get_terminator}{}
- Returns the current terminator for the channel.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_close}{}
- Called when the channel is closed. The default method silently closes
- the channel's socket.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_read}{}
- Called when a read event fires on the channel's socket in the
- asynchronous loop. The default method checks for the termination
- condition established by \method{set_terminator()}, which can be either
- the appearance of a particular string in the input stream or the receipt
- of a particular number of characters. When the terminator is found,
- \method{handle_read} calls the \method{found_terminator()} method after
- calling \method{collect_incoming_data()} with any data preceding the
- terminating condition.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_write}{}
- Called when the application may write data to the channel.
- The default method calls the \method{initiate_send()} method, which in turn
- will call \method{refill_buffer()} to collect data from the producer
- fifo associated with the channel.
-\end{methoddesc}
-
-\begin{methoddesc}{push}{data}
- Creates a \class{simple_producer} object (\emph{see below}) containing the data and
- pushes it on to the channel's \code{producer_fifo} to ensure its
- transmission. This is all you need to do to have the channel write
- the data out to the network, although it is possible to use your
- own producers in more complex schemes to implement encryption and
- chunking, for example.
-\end{methoddesc}
-
-\begin{methoddesc}{push_with_producer}{producer}
- Takes a producer object and adds it to the producer fifo associated with
- the channel. When all currently-pushed producers have been exhausted
- the channel will consume this producer's data by calling its
- \method{more()} method and send the data to the remote endpoint.
-\end{methoddesc}
-
-\begin{methoddesc}{readable}{}
- Should return \code{True} for the channel to be included in the set of
- channels tested by the \cfunction{select()} loop for readability.
-\end{methoddesc}
-
-\begin{methoddesc}{refill_buffer}{}
- Refills the output buffer by calling the \method{more()} method of the
- producer at the head of the fifo. If it is exhausted then the
- producer is popped off the fifo and the next producer is activated.
- If the current producer is, or becomes, \code{None} then the channel
- is closed.
-\end{methoddesc}
-
-\begin{methoddesc}{set_terminator}{term}
- Sets the terminating condition to be recognised on the channel. \code{term}
- may be any of three types of value, corresponding to three different ways
- to handle incoming protocol data.
-
- \begin{tableii}{l|l}{}{term}{Description}
- \lineii{\emph{string}}{Will call \method{found_terminator()} when the
- string is found in the input stream}
- \lineii{\emph{integer}}{Will call \method{found_terminator()} when the
- indicated number of characters have been received}
- \lineii{\code{None}}{The channel continues to collect data forever}
- \end{tableii}
-
- Note that any data following the terminator will be available for reading by
- the channel after \method{found_terminator()} is called.
-\end{methoddesc}
-
-\begin{methoddesc}{writable}{}
- Should return \code{True} as long as items remain on the producer fifo,
- or the channel is connected and the channel's output buffer is non-empty.
-\end{methoddesc}
-
-\subsection{asynchat - Auxiliary Classes and Functions}
-
-\begin{classdesc}{simple_producer}{data\optional{, buffer_size=512}}
- A \class{simple_producer} takes a chunk of data and an optional buffer size.
- Repeated calls to its \method{more()} method yield successive chunks of the
- data no larger than \var{buffer_size}.
-\end{classdesc}
-
-\begin{methoddesc}{more}{}
- Produces the next chunk of information from the producer, or returns the empty string.
-\end{methoddesc}
-
-\begin{classdesc}{fifo}{\optional{list=None}}
- Each channel maintains a \class{fifo} holding data which has been pushed by the
- application but not yet popped for writing to the channel.
- A \class{fifo} is a list used to hold data and/or producers until they are required.
- If the \var{list} argument is provided then it should contain producers or
- data items to be written to the channel.
-\end{classdesc}
-
-\begin{methoddesc}{is_empty}{}
- Returns \code{True} iff the fifo is empty.
-\end{methoddesc}
-
-\begin{methoddesc}{first}{}
- Returns the least-recently \method{push()}ed item from the fifo.
-\end{methoddesc}
-
-\begin{methoddesc}{push}{data}
- Adds the given data (which may be a string or a producer object) to the
- producer fifo.
-\end{methoddesc}
-
-\begin{methoddesc}{pop}{}
- If the fifo is not empty, returns \code{True, first()}, deleting the popped
- item. Returns \code{False, None} for an empty fifo.
-\end{methoddesc}
-
-The \module{asynchat} module also defines one utility function, which may be
-of use in network and textual analysis operations.
-
-\begin{funcdesc}{find_prefix_at_end}{haystack, needle}
- Returns \code{True} if string \var{haystack} ends with any non-empty
- prefix of string \var{needle}.
-\end{funcdesc}
-
-\subsection{asynchat Example \label{asynchat-example}}
-
-The following partial example shows how HTTP requests can be read with
-\class{async_chat}. A web server might create an \class{http_request_handler} object for
-each incoming client connection. Notice that initially the
-channel terminator is set to match the blank line at the end of the HTTP
-headers, and a flag indicates that the headers are being read.
-
-Once the headers have been read, if the request is of type POST
-(indicating that further data are present in the input stream) then the
-\code{Content-Length:} header is used to set a numeric terminator to
-read the right amount of data from the channel.
-
-The \method{handle_request()} method is called once all relevant input
-has been marshalled, after setting the channel terminator to \code{None}
-to ensure that any extraneous data sent by the web client are ignored.
-
-\begin{verbatim}
-class http_request_handler(asynchat.async_chat):
-
- def __init__(self, conn, addr, sessions, log):
- asynchat.async_chat.__init__(self, conn=conn)
- self.addr = addr
- self.sessions = sessions
- self.ibuffer = []
- self.obuffer = ""
- self.set_terminator("\r\n\r\n")
- self.reading_headers = True
- self.handling = False
- self.cgi_data = None
- self.log = log
-
- def collect_incoming_data(self, data):
- """Buffer the data"""
- self.ibuffer.append(data)
-
- def found_terminator(self):
- if self.reading_headers:
- self.reading_headers = False
- self.parse_headers("".join(self.ibuffer))
- self.ibuffer = []
- if self.op.upper() == "POST":
- clen = self.headers.getheader("content-length")
- self.set_terminator(int(clen))
- else:
- self.handling = True
- self.set_terminator(None)
- self.handle_request()
- elif not self.handling:
- self.set_terminator(None) # browsers sometimes over-send
- self.cgi_data = parse(self.headers, "".join(self.ibuffer))
- self.handling = True
- self.ibuffer = []
- self.handle_request()
-\end{verbatim}
-
diff --git a/Doc/lib/libasyncore.tex b/Doc/lib/libasyncore.tex
deleted file mode 100644
index 89c717810b..0000000000
--- a/Doc/lib/libasyncore.tex
+++ /dev/null
@@ -1,251 +0,0 @@
-\section{\module{asyncore} ---
- Asynchronous socket handler}
-
-\declaremodule{builtin}{asyncore}
-\modulesynopsis{A base class for developing asynchronous socket
- handling services.}
-\moduleauthor{Sam Rushing}{rushing@nightmare.com}
-\sectionauthor{Christopher Petrilli}{petrilli@amber.org}
-\sectionauthor{Steve Holden}{sholden@holdenweb.com}
-% Heavily adapted from original documentation by Sam Rushing.
-
-This module provides the basic infrastructure for writing asynchronous
-socket service clients and servers.
-
-There are only two ways to have a program on a single processor do
-``more than one thing at a time.'' Multi-threaded programming is the
-simplest and most popular way to do it, but there is another very
-different technique, that lets you have nearly all the advantages of
-multi-threading, without actually using multiple threads. It's really
-only practical if your program is largely I/O bound. If your program
-is processor bound, then pre-emptive scheduled threads are probably what
-you really need. Network servers are rarely processor bound, however.
-
-If your operating system supports the \cfunction{select()} system call
-in its I/O library (and nearly all do), then you can use it to juggle
-multiple communication channels at once; doing other work while your
-I/O is taking place in the ``background.'' Although this strategy can
-seem strange and complex, especially at first, it is in many ways
-easier to understand and control than multi-threaded programming.
-The \module{asyncore} module solves many of the difficult problems for
-you, making the task of building sophisticated high-performance
-network servers and clients a snap. For ``conversational'' applications
-and protocols the companion \refmodule{asynchat} module is invaluable.
-
-The basic idea behind both modules is to create one or more network
-\emph{channels}, instances of class \class{asyncore.dispatcher} and
-\class{asynchat.async_chat}. Creating the channels adds them to a global
-map, used by the \function{loop()} function if you do not provide it
-with your own \var{map}.
-
-Once the initial channel(s) is(are) created, calling the \function{loop()}
-function activates channel service, which continues until the last
-channel (including any that have been added to the map during asynchronous
-service) is closed.
-
-\begin{funcdesc}{loop}{\optional{timeout\optional{, use_poll\optional{,
- map}}}}
- Enter a polling loop that only terminates after all open channels
- have been closed. All arguments are optional. The \var{timeout}
- argument sets the timeout parameter for the appropriate
- \function{select()} or \function{poll()} call, measured in seconds;
- the default is 30 seconds. The \var{use_poll} parameter, if true,
- indicates that \function{poll()} should be used in preference to
- \function{select()} (the default is \code{False}). The \var{map} parameter
- is a dictionary whose items are the channels to watch. As channels
- are closed they are deleted from their map. If \var{map} is
- omitted, a global map is used (this map is updated by the default
- class \method{__init__()}
- -- make sure you extend, rather than override, \method{__init__()}
- if you want to retain this behavior).
-
- Channels (instances of \class{asyncore.dispatcher}, \class{asynchat.async_chat}
- and subclasses thereof) can freely be mixed in the map.
-\end{funcdesc}
-
-\begin{classdesc}{dispatcher}{}
- The \class{dispatcher} class is a thin wrapper around a low-level socket object.
- To make it more useful, it has a few methods for event-handling which are called
- from the asynchronous loop.
- Otherwise, it can be treated as a normal non-blocking socket object.
-
- Two class attributes can be modified, to improve performance,
- or possibly even to conserve memory.
-
- \begin{datadesc}{ac_in_buffer_size}
- The asynchronous input buffer size (default \code{4096}).
- \end{datadesc}
-
- \begin{datadesc}{ac_out_buffer_size}
- The asynchronous output buffer size (default \code{4096}).
- \end{datadesc}
-
- The firing of low-level events at certain times or in certain connection
- states tells the asynchronous loop that certain higher-level events have
- taken place. For example, if we have asked for a socket to connect to
- another host, we know that the connection has been made when the socket
- becomes writable for the first time (at this point you know that you may
- write to it with the expectation of success). The implied higher-level
- events are:
-
- \begin{tableii}{l|l}{code}{Event}{Description}
- \lineii{handle_connect()}{Implied by the first write event}
- \lineii{handle_close()}{Implied by a read event with no data available}
- \lineii{handle_accept()}{Implied by a read event on a listening socket}
- \end{tableii}
-
- During asynchronous processing, each mapped channel's \method{readable()}
- and \method{writable()} methods are used to determine whether the channel's
- socket should be added to the list of channels \cfunction{select()}ed or
- \cfunction{poll()}ed for read and write events.
-
-\end{classdesc}
-
-Thus, the set of channel events is larger than the basic socket events.
-The full set of methods that can be overridden in your subclass follows:
-
-\begin{methoddesc}{handle_read}{}
- Called when the asynchronous loop detects that a \method{read()}
- call on the channel's socket will succeed.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_write}{}
- Called when the asynchronous loop detects that a writable socket
- can be written.
- Often this method will implement the necessary buffering for
- performance. For example:
-
-\begin{verbatim}
-def handle_write(self):
- sent = self.send(self.buffer)
- self.buffer = self.buffer[sent:]
-\end{verbatim}
-\end{methoddesc}
-
-\begin{methoddesc}{handle_expt}{}
- Called when there is out of band (OOB) data for a socket
- connection. This will almost never happen, as OOB is
- tenuously supported and rarely used.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_connect}{}
- Called when the active opener's socket actually makes a connection.
- Might send a ``welcome'' banner, or initiate a protocol
- negotiation with the remote endpoint, for example.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_close}{}
- Called when the socket is closed.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_error}{}
- Called when an exception is raised and not otherwise handled. The default
- version prints a condensed traceback.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_accept}{}
- Called on listening channels (passive openers) when a
- connection can be established with a new remote endpoint that
- has issued a \method{connect()} call for the local endpoint.
-\end{methoddesc}
-
-\begin{methoddesc}{readable}{}
- Called each time around the asynchronous loop to determine whether a
- channel's socket should be added to the list on which read events can
- occur. The default method simply returns \code{True},
- indicating that by default, all channels will be interested in
- read events.
-\end{methoddesc}
-
-\begin{methoddesc}{writable}{}
- Called each time around the asynchronous loop to determine whether a
- channel's socket should be added to the list on which write events can
- occur. The default method simply returns \code{True},
- indicating that by default, all channels will be interested in
- write events.
-\end{methoddesc}
-
-In addition, each channel delegates or extends many of the socket methods.
-Most of these are nearly identical to their socket partners.
-
-\begin{methoddesc}{create_socket}{family, type}
- This is identical to the creation of a normal socket, and
- will use the same options for creation. Refer to the
- \refmodule{socket} documentation for information on creating
- sockets.
-\end{methoddesc}
-
-\begin{methoddesc}{connect}{address}
- As with the normal socket object, \var{address} is a
- tuple with the first element the host to connect to, and the
- second the port number.
-\end{methoddesc}
-
-\begin{methoddesc}{send}{data}
- Send \var{data} to the remote end-point of the socket.
-\end{methoddesc}
-
-\begin{methoddesc}{recv}{buffer_size}
- Read at most \var{buffer_size} bytes from the socket's remote end-point.
- An empty string implies that the channel has been closed from the other
- end.
-\end{methoddesc}
-
-\begin{methoddesc}{listen}{backlog}
- Listen for connections made to the socket. The \var{backlog}
- argument specifies the maximum number of queued connections
- and should be at least 1; the maximum value is
- system-dependent (usually 5).
-\end{methoddesc}
-
-\begin{methoddesc}{bind}{address}
- Bind the socket to \var{address}. The socket must not already
- be bound. (The format of \var{address} depends on the address
- family --- see above.)
-\end{methoddesc}
-
-\begin{methoddesc}{accept}{}
- Accept a connection. The socket must be bound to an address
- and listening for connections. The return value is a pair
- \code{(\var{conn}, \var{address})} where \var{conn} is a
- \emph{new} socket object usable to send and receive data on
- the connection, and \var{address} is the address bound to the
- socket on the other end of the connection.
-\end{methoddesc}
-
-\begin{methoddesc}{close}{}
- Close the socket. All future operations on the socket object
- will fail. The remote end-point will receive no more data (after
- queued data is flushed). Sockets are automatically closed
- when they are garbage-collected.
-\end{methoddesc}
-
-
-\subsection{asyncore Example basic HTTP client \label{asyncore-example}}
-
-As a basic example, below is a very basic HTTP client that uses the
-\class{dispatcher} class to implement its socket handling:
-
-\begin{verbatim}
-class http_client(asyncore.dispatcher):
- def __init__(self, host,path):
- asyncore.dispatcher.__init__(self)
- self.path = path
- self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
- self.connect( (host, 80) )
- self.buffer = 'GET %s HTTP/1.0\r\n\r\n' % self.path
-
- def handle_connect(self):
- pass
-
- def handle_read(self):
- data = self.recv(8192)
- print data
-
- def writable(self):
- return (len(self.buffer) > 0)
-
- def handle_write(self):
- sent = self.send(self.buffer)
- self.buffer = self.buffer[sent:]
-\end{verbatim}
diff --git a/Doc/lib/libatexit.tex b/Doc/lib/libatexit.tex
deleted file mode 100644
index c9775d1b6d..0000000000
--- a/Doc/lib/libatexit.tex
+++ /dev/null
@@ -1,89 +0,0 @@
-\section{\module{atexit} ---
- Exit handlers}
-
-\declaremodule{standard}{atexit}
-\moduleauthor{Skip Montanaro}{skip@mojam.com}
-\sectionauthor{Skip Montanaro}{skip@mojam.com}
-\modulesynopsis{Register and execute cleanup functions.}
-
-\versionadded{2.0}
-
-The \module{atexit} module defines a single function to register
-cleanup functions. Functions thus registered are automatically
-executed upon normal interpreter termination.
-
-Note: the functions registered via this module are not called when the program is killed by a
-signal, when a Python fatal internal error is detected, or when
-\function{os._exit()} is called.
-
-This is an alternate interface to the functionality provided by the
-\code{sys.exitfunc} variable.
-\withsubitem{(in sys)}{\ttindex{exitfunc}}
-
-Note: This module is unlikely to work correctly when used with other code
-that sets \code{sys.exitfunc}. In particular, other core Python modules are
-free to use \module{atexit} without the programmer's knowledge. Authors who
-use \code{sys.exitfunc} should convert their code to use
-\module{atexit} instead. The simplest way to convert code that sets
-\code{sys.exitfunc} is to import \module{atexit} and register the function
-that had been bound to \code{sys.exitfunc}.
-
-\begin{funcdesc}{register}{func\optional{, *args\optional{, **kargs}}}
-Register \var{func} as a function to be executed at termination. Any
-optional arguments that are to be passed to \var{func} must be passed
-as arguments to \function{register()}.
-
-At normal program termination (for instance, if
-\function{sys.exit()} is called or the main module's execution
-completes), all functions registered are called in last in, first out
-order. The assumption is that lower level modules will normally be
-imported before higher level modules and thus must be cleaned up
-later.
-\end{funcdesc}
-
-
-\begin{seealso}
- \seemodule{readline}{Useful example of \module{atexit} to read and
- write \refmodule{readline} history files.}
-\end{seealso}
-
-
-\subsection{\module{atexit} Example \label{atexit-example}}
-
-The following simple example demonstrates how a module can initialize
-a counter from a file when it is imported and save the counter's
-updated value automatically when the program terminates without
-relying on the application making an explicit call into this module at
-termination.
-
-\begin{verbatim}
-try:
- _count = int(open("/tmp/counter").read())
-except IOError:
- _count = 0
-
-def incrcounter(n):
- global _count
- _count = _count + n
-
-def savecounter():
- open("/tmp/counter", "w").write("%d" % _count)
-
-import atexit
-atexit.register(savecounter)
-\end{verbatim}
-
-Positional and keyword arguments may also be passed to
-\function{register()} to be passed along to the registered function
-when it is called:
-
-\begin{verbatim}
-def goodbye(name, adjective):
- print 'Goodbye, %s, it was %s to meet you.' % (name, adjective)
-
-import atexit
-atexit.register(goodbye, 'Donny', 'nice')
-
-# or:
-atexit.register(goodbye, adjective='nice', name='Donny')
-\end{verbatim}
diff --git a/Doc/lib/libaudioop.tex b/Doc/lib/libaudioop.tex
deleted file mode 100644
index 06b1c27616..0000000000
--- a/Doc/lib/libaudioop.tex
+++ /dev/null
@@ -1,255 +0,0 @@
-\section{\module{audioop} ---
- Manipulate raw audio data}
-
-\declaremodule{builtin}{audioop}
-\modulesynopsis{Manipulate raw audio data.}
-
-
-The \module{audioop} module contains some useful operations on sound
-fragments. It operates on sound fragments consisting of signed
-integer samples 8, 16 or 32 bits wide, stored in Python strings. This
-is the same format as used by the \refmodule{al} and \refmodule{sunaudiodev}
-modules. All scalar items are integers, unless specified otherwise.
-
-% This para is mostly here to provide an excuse for the index entries...
-This module provides support for u-LAW and Intel/DVI ADPCM encodings.
-\index{Intel/DVI ADPCM}
-\index{ADPCM, Intel/DVI}
-\index{u-LAW}
-
-A few of the more complicated operations only take 16-bit samples,
-otherwise the sample size (in bytes) is always a parameter of the
-operation.
-
-The module defines the following variables and functions:
-
-\begin{excdesc}{error}
-This exception is raised on all errors, such as unknown number of bytes
-per sample, etc.
-\end{excdesc}
-
-\begin{funcdesc}{add}{fragment1, fragment2, width}
-Return a fragment which is the addition of the two samples passed as
-parameters. \var{width} is the sample width in bytes, either
-\code{1}, \code{2} or \code{4}. Both fragments should have the same
-length.
-\end{funcdesc}
-
-\begin{funcdesc}{adpcm2lin}{adpcmfragment, width, state}
-Decode an Intel/DVI ADPCM coded fragment to a linear fragment. See
-the description of \function{lin2adpcm()} for details on ADPCM coding.
-Return a tuple \code{(\var{sample}, \var{newstate})} where the sample
-has the width specified in \var{width}.
-\end{funcdesc}
-
-\begin{funcdesc}{adpcm32lin}{adpcmfragment, width, state}
-Decode an alternative 3-bit ADPCM code. See \function{lin2adpcm3()}
-for details.
-\end{funcdesc}
-
-\begin{funcdesc}{avg}{fragment, width}
-Return the average over all samples in the fragment.
-\end{funcdesc}
-
-\begin{funcdesc}{avgpp}{fragment, width}
-Return the average peak-peak value over all samples in the fragment.
-No filtering is done, so the usefulness of this routine is
-questionable.
-\end{funcdesc}
-
-\begin{funcdesc}{bias}{fragment, width, bias}
-Return a fragment that is the original fragment with a bias added to
-each sample.
-\end{funcdesc}
-
-\begin{funcdesc}{cross}{fragment, width}
-Return the number of zero crossings in the fragment passed as an
-argument.
-\end{funcdesc}
-
-\begin{funcdesc}{findfactor}{fragment, reference}
-Return a factor \var{F} such that
-\code{rms(add(\var{fragment}, mul(\var{reference}, -\var{F})))} is
-minimal, i.e., return the factor with which you should multiply
-\var{reference} to make it match as well as possible to
-\var{fragment}. The fragments should both contain 2-byte samples.
-
-The time taken by this routine is proportional to
-\code{len(\var{fragment})}.
-\end{funcdesc}
-
-\begin{funcdesc}{findfit}{fragment, reference}
-Try to match \var{reference} as well as possible to a portion of
-\var{fragment} (which should be the longer fragment). This is
-(conceptually) done by taking slices out of \var{fragment}, using
-\function{findfactor()} to compute the best match, and minimizing the
-result. The fragments should both contain 2-byte samples. Return a
-tuple \code{(\var{offset}, \var{factor})} where \var{offset} is the
-(integer) offset into \var{fragment} where the optimal match started
-and \var{factor} is the (floating-point) factor as per
-\function{findfactor()}.
-\end{funcdesc}
-
-\begin{funcdesc}{findmax}{fragment, length}
-Search \var{fragment} for a slice of length \var{length} samples (not
-bytes!)\ with maximum energy, i.e., return \var{i} for which
-\code{rms(fragment[i*2:(i+length)*2])} is maximal. The fragments
-should both contain 2-byte samples.
-
-The routine takes time proportional to \code{len(\var{fragment})}.
-\end{funcdesc}
-
-\begin{funcdesc}{getsample}{fragment, width, index}
-Return the value of sample \var{index} from the fragment.
-\end{funcdesc}
-
-\begin{funcdesc}{lin2lin}{fragment, width, newwidth}
-Convert samples between 1-, 2- and 4-byte formats.
-\end{funcdesc}
-
-\begin{funcdesc}{lin2adpcm}{fragment, width, state}
-Convert samples to 4 bit Intel/DVI ADPCM encoding. ADPCM coding is an
-adaptive coding scheme, whereby each 4 bit number is the difference
-between one sample and the next, divided by a (varying) step. The
-Intel/DVI ADPCM algorithm has been selected for use by the IMA, so it
-may well become a standard.
-
-\var{state} is a tuple containing the state of the coder. The coder
-returns a tuple \code{(\var{adpcmfrag}, \var{newstate})}, and the
-\var{newstate} should be passed to the next call of
-\function{lin2adpcm()}. In the initial call, \code{None} can be
-passed as the state. \var{adpcmfrag} is the ADPCM coded fragment
-packed 2 4-bit values per byte.
-\end{funcdesc}
-
-\begin{funcdesc}{lin2adpcm3}{fragment, width, state}
-This is an alternative ADPCM coder that uses only 3 bits per sample.
-It is not compatible with the Intel/DVI ADPCM coder and its output is
-not packed (due to laziness on the side of the author). Its use is
-discouraged.
-\end{funcdesc}
-
-\begin{funcdesc}{lin2ulaw}{fragment, width}
-Convert samples in the audio fragment to u-LAW encoding and return
-this as a Python string. u-LAW is an audio encoding format whereby
-you get a dynamic range of about 14 bits using only 8 bit samples. It
-is used by the Sun audio hardware, among others.
-\end{funcdesc}
-
-\begin{funcdesc}{minmax}{fragment, width}
-Return a tuple consisting of the minimum and maximum values of all
-samples in the sound fragment.
-\end{funcdesc}
-
-\begin{funcdesc}{max}{fragment, width}
-Return the maximum of the \emph{absolute value} of all samples in a
-fragment.
-\end{funcdesc}
-
-\begin{funcdesc}{maxpp}{fragment, width}
-Return the maximum peak-peak value in the sound fragment.
-\end{funcdesc}
-
-\begin{funcdesc}{mul}{fragment, width, factor}
-Return a fragment that has all samples in the original fragment
-multiplied by the floating-point value \var{factor}. Overflow is
-silently ignored.
-\end{funcdesc}
-
-\begin{funcdesc}{ratecv}{fragment, width, nchannels, inrate, outrate,
- state\optional{, weightA\optional{, weightB}}}
-Convert the frame rate of the input fragment.
-
-\var{state} is a tuple containing the state of the converter. The
-converter returns a tuple \code{(\var{newfragment}, \var{newstate})},
-and \var{newstate} should be passed to the next call of
-\function{ratecv()}. The initial call should pass \code{None}
-as the state.
-
-The \var{weightA} and \var{weightB} arguments are parameters for a
-simple digital filter and default to \code{1} and \code{0} respectively.
-\end{funcdesc}
-
-\begin{funcdesc}{reverse}{fragment, width}
-Reverse the samples in a fragment and returns the modified fragment.
-\end{funcdesc}
-
-\begin{funcdesc}{rms}{fragment, width}
-Return the root-mean-square of the fragment, i.e.
-\begin{displaymath}
-\catcode`_=8
-\sqrt{\frac{\sum{{S_{i}}^{2}}}{n}}
-\end{displaymath}
-This is a measure of the power in an audio signal.
-\end{funcdesc}
-
-\begin{funcdesc}{tomono}{fragment, width, lfactor, rfactor}
-Convert a stereo fragment to a mono fragment. The left channel is
-multiplied by \var{lfactor} and the right channel by \var{rfactor}
-before adding the two channels to give a mono signal.
-\end{funcdesc}
-
-\begin{funcdesc}{tostereo}{fragment, width, lfactor, rfactor}
-Generate a stereo fragment from a mono fragment. Each pair of samples
-in the stereo fragment are computed from the mono sample, whereby left
-channel samples are multiplied by \var{lfactor} and right channel
-samples by \var{rfactor}.
-\end{funcdesc}
-
-\begin{funcdesc}{ulaw2lin}{fragment, width}
-Convert sound fragments in u-LAW encoding to linearly encoded sound
-fragments. u-LAW encoding always uses 8 bits samples, so \var{width}
-refers only to the sample width of the output fragment here.
-\end{funcdesc}
-
-Note that operations such as \function{mul()} or \function{max()} make
-no distinction between mono and stereo fragments, i.e.\ all samples
-are treated equal. If this is a problem the stereo fragment should be
-split into two mono fragments first and recombined later. Here is an
-example of how to do that:
-
-\begin{verbatim}
-def mul_stereo(sample, width, lfactor, rfactor):
- lsample = audioop.tomono(sample, width, 1, 0)
- rsample = audioop.tomono(sample, width, 0, 1)
- lsample = audioop.mul(sample, width, lfactor)
- rsample = audioop.mul(sample, width, rfactor)
- lsample = audioop.tostereo(lsample, width, 1, 0)
- rsample = audioop.tostereo(rsample, width, 0, 1)
- return audioop.add(lsample, rsample, width)
-\end{verbatim}
-
-If you use the ADPCM coder to build network packets and you want your
-protocol to be stateless (i.e.\ to be able to tolerate packet loss)
-you should not only transmit the data but also the state. Note that
-you should send the \var{initial} state (the one you passed to
-\function{lin2adpcm()}) along to the decoder, not the final state (as
-returned by the coder). If you want to use \function{struct.struct()}
-to store the state in binary you can code the first element (the
-predicted value) in 16 bits and the second (the delta index) in 8.
-
-The ADPCM coders have never been tried against other ADPCM coders,
-only against themselves. It could well be that I misinterpreted the
-standards in which case they will not be interoperable with the
-respective standards.
-
-The \function{find*()} routines might look a bit funny at first sight.
-They are primarily meant to do echo cancellation. A reasonably
-fast way to do this is to pick the most energetic piece of the output
-sample, locate that in the input sample and subtract the whole output
-sample from the input sample:
-
-\begin{verbatim}
-def echocancel(outputdata, inputdata):
- pos = audioop.findmax(outputdata, 800) # one tenth second
- out_test = outputdata[pos*2:]
- in_test = inputdata[pos*2:]
- ipos, factor = audioop.findfit(in_test, out_test)
- # Optional (for better cancellation):
- # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
- # out_test)
- prefill = '\0'*(pos+ipos)*2
- postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
- outputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill
- return audioop.add(inputdata, outputdata, 2)
-\end{verbatim}
diff --git a/Doc/lib/libbase64.tex b/Doc/lib/libbase64.tex
deleted file mode 100644
index 91f4818d1e..0000000000
--- a/Doc/lib/libbase64.tex
+++ /dev/null
@@ -1,64 +0,0 @@
-\section{\module{base64} ---
- Encode and decode MIME base64 data}
-
-\declaremodule{standard}{base64}
-\modulesynopsis{Encode and decode files using the MIME base64 data.}
-
-
-\indexii{base64}{encoding}
-\index{MIME!base64 encoding}
-
-This module performs base64 encoding and decoding of arbitrary binary
-strings into text strings that can be safely sent by email or included
-as part of an HTTP POST request. The
-encoding scheme is defined in \rfc{1521} (\emph{MIME
-(Multipurpose Internet Mail Extensions) Part One: Mechanisms for
-Specifying and Describing the Format of Internet Message Bodies},
-section 5.2, ``Base64 Content-Transfer-Encoding'') and is used for
-MIME email and various other Internet-related applications; it is not
-the same as the output produced by the \program{uuencode} program.
-For example, the string \code{'www.python.org'} is encoded as the
-string \code{'d3d3LnB5dGhvbi5vcmc=\e n'}.
-
-
-\begin{funcdesc}{decode}{input, output}
-Decode the contents of the \var{input} file and write the resulting
-binary data to the \var{output} file.
-\var{input} and \var{output} must either be file objects or objects that
-mimic the file object interface. \var{input} will be read until
-\code{\var{input}.read()} returns an empty string.
-\end{funcdesc}
-
-\begin{funcdesc}{decodestring}{s}
-Decode the string \var{s}, which must contain one or more lines of
-base64 encoded data, and return a string containing the resulting
-binary data.
-\end{funcdesc}
-
-\begin{funcdesc}{encode}{input, output}
-Encode the contents of the \var{input} file and write the resulting
-base64 encoded data to the \var{output} file.
-\var{input} and \var{output} must either be file objects or objects that
-mimic the file object interface. \var{input} will be read until
-\code{\var{input}.read()} returns an empty string. \function{encode()}
-returns the encoded data plus a trailing newline character
-(\code{'\e n'}).
-\end{funcdesc}
-
-\begin{funcdesc}{encodestring}{s}
-Encode the string \var{s}, which can contain arbitrary binary data,
-and return a string containing one or more lines of
-base64-encoded data. \function{encodestring()} returns a
-string containing one or more lines of base64-encoded data
-always including an extra trailing newline (\code{'\e n'}).
-\end{funcdesc}
-
-\begin{seealso}
- \seemodule{binascii}{Support module containing \ASCII-to-binary
- and binary-to-\ASCII{} conversions.}
- \seerfc{1521}{MIME (Multipurpose Internet Mail Extensions) Part One:
- Mechanisms for Specifying and Describing the Format of
- Internet Message Bodies}{Section 5.2, ``Base64
- Content-Transfer-Encoding,'' provides the definition of the
- base64 encoding.}
-\end{seealso}
diff --git a/Doc/lib/libbasehttp.tex b/Doc/lib/libbasehttp.tex
deleted file mode 100644
index e00ae360fa..0000000000
--- a/Doc/lib/libbasehttp.tex
+++ /dev/null
@@ -1,240 +0,0 @@
-\section{\module{BaseHTTPServer} ---
- Basic HTTP server}
-
-\declaremodule{standard}{BaseHTTPServer}
-\modulesynopsis{Basic HTTP server (base class for
- \class{SimpleHTTPServer} and \class{CGIHTTPServer}).}
-
-
-\indexii{WWW}{server}
-\indexii{HTTP}{protocol}
-\index{URL}
-\index{httpd}
-
-This module defines two classes for implementing HTTP servers
-(Web servers). Usually, this module isn't used directly, but is used
-as a basis for building functioning Web servers. See the
-\module{SimpleHTTPServer}\refstmodindex{SimpleHTTPServer} and
-\refmodule{CGIHTTPServer}\refstmodindex{CGIHTTPServer} modules.
-
-The first class, \class{HTTPServer}, is a
-\class{SocketServer.TCPServer} subclass. It creates and listens at the
-HTTP socket, dispatching the requests to a handler. Code to create and
-run the server looks like this:
-
-\begin{verbatim}
-def run(server_class=BaseHTTPServer.HTTPServer,
- handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
- server_address = ('', 8000)
- httpd = server_class(server_address, handler_class)
- httpd.serve_forever()
-\end{verbatim}
-
-\begin{classdesc}{HTTPServer}{server_address, RequestHandlerClass}
-This class builds on the \class{TCPServer} class by
-storing the server address as instance
-variables named \member{server_name} and \member{server_port}. The
-server is accessible by the handler, typically through the handler's
-\member{server} instance variable.
-\end{classdesc}
-
-\begin{classdesc}{BaseHTTPRequestHandler}{request, client_address, server}
-This class is used
-to handle the HTTP requests that arrive at the server. By itself,
-it cannot respond to any actual HTTP requests; it must be subclassed
-to handle each request method (e.g. GET or POST).
-\class{BaseHTTPRequestHandler} provides a number of class and instance
-variables, and methods for use by subclasses.
-
-The handler will parse the request and the headers, then call a
-method specific to the request type. The method name is constructed
-from the request. For example, for the request method \samp{SPAM}, the
-\method{do_SPAM()} method will be called with no arguments. All of
-the relevant information is stored in instance variables of the
-handler. Subclasses should not need to override or extend the
-\method{__init__()} method.
-\end{classdesc}
-
-
-\class{BaseHTTPRequestHandler} has the following instance variables:
-
-\begin{memberdesc}{client_address}
-Contains a tuple of the form \code{(\var{host}, \var{port})} referring
-to the client's address.
-\end{memberdesc}
-
-\begin{memberdesc}{command}
-Contains the command (request type). For example, \code{'GET'}.
-\end{memberdesc}
-
-\begin{memberdesc}{path}
-Contains the request path.
-\end{memberdesc}
-
-\begin{memberdesc}{request_version}
-Contains the version string from the request. For example,
-\code{'HTTP/1.0'}.
-\end{memberdesc}
-
-\begin{memberdesc}{headers}
-Holds an instance of the class specified by the \member{MessageClass}
-class variable. This instance parses and manages the headers in
-the HTTP request.
-\end{memberdesc}
-
-\begin{memberdesc}{rfile}
-Contains an input stream, positioned at the start of the optional
-input data.
-\end{memberdesc}
-
-\begin{memberdesc}{wfile}
-Contains the output stream for writing a response back to the client.
-Proper adherence to the HTTP protocol must be used when writing
-to this stream.
-\end{memberdesc}
-
-
-\class{BaseHTTPRequestHandler} has the following class variables:
-
-\begin{memberdesc}{server_version}
-Specifies the server software version. You may want to override
-this.
-The format is multiple whitespace-separated strings,
-where each string is of the form name[/version].
-For example, \code{'BaseHTTP/0.2'}.
-\end{memberdesc}
-
-\begin{memberdesc}{sys_version}
-Contains the Python system version, in a form usable by the
-\member{version_string} method and the \member{server_version} class
-variable. For example, \code{'Python/1.4'}.
-\end{memberdesc}
-
-\begin{memberdesc}{error_message_format}
-Specifies a format string for building an error response to the
-client. It uses parenthesized, keyed format specifiers, so the
-format operand must be a dictionary. The \var{code} key should
-be an integer, specifying the numeric HTTP error code value.
-\var{message} should be a string containing a (detailed) error
-message of what occurred, and \var{explain} should be an
-explanation of the error code number. Default \var{message}
-and \var{explain} values can found in the \var{responses}
-class variable.
-\end{memberdesc}
-
-\begin{memberdesc}{protocol_version}
-This specifies the HTTP protocol version used in responses. If set
-to \code{'HTTP/1.1'}, the server will permit HTTP persistent
-connections; however, your server \emph{must} then include an
-accurate \code{Content-Length} header (using \method{send_header()})
-in all of its responses to clients. For backwards compatibility,
-the setting defaults to \code{'HTTP/1.0'}.
-\end{memberdesc}
-
-\begin{memberdesc}{MessageClass}
-Specifies a \class{rfc822.Message}-like class to parse HTTP
-headers. Typically, this is not overridden, and it defaults to
-\class{mimetools.Message}.
-\withsubitem{(in module mimetools)}{\ttindex{Message}}
-\end{memberdesc}
-
-\begin{memberdesc}{responses}
-This variable contains a mapping of error code integers to two-element
-tuples containing a short and long message. For example,
-\code{\{\var{code}: (\var{shortmessage}, \var{longmessage})\}}. The
-\var{shortmessage} is usually used as the \var{message} key in an
-error response, and \var{longmessage} as the \var{explain} key
-(see the \member{error_message_format} class variable).
-\end{memberdesc}
-
-
-A \class{BaseHTTPRequestHandler} instance has the following methods:
-
-\begin{methoddesc}{handle}{}
-Calls \method{handle_one_request()} once (or, if persistent connections
-are enabled, multiple times) to handle incoming HTTP requests.
-You should never need to override it; instead, implement appropriate
-\method{do_*()} methods.
-\end{methoddesc}
-
-\begin{methoddesc}{handle_one_request}{}
-This method will parse and dispatch
-the request to the appropriate \method{do_*()} method. You should
-never need to override it.
-\end{methoddesc}
-
-\begin{methoddesc}{send_error}{code\optional{, message}}
-Sends and logs a complete error reply to the client. The numeric
-\var{code} specifies the HTTP error code, with \var{message} as
-optional, more specific text. A complete set of headers is sent,
-followed by text composed using the \member{error_message_format}
-class variable.
-\end{methoddesc}
-
-\begin{methoddesc}{send_response}{code\optional{, message}}
-Sends a response header and logs the accepted request. The HTTP
-response line is sent, followed by \emph{Server} and \emph{Date}
-headers. The values for these two headers are picked up from the
-\method{version_string()} and \method{date_time_string()} methods,
-respectively.
-\end{methoddesc}
-
-\begin{methoddesc}{send_header}{keyword, value}
-Writes a specific MIME header to the output stream. \var{keyword}
-should specify the header keyword, with \var{value} specifying
-its value.
-\end{methoddesc}
-
-\begin{methoddesc}{end_headers}{}
-Sends a blank line, indicating the end of the MIME headers in
-the response.
-\end{methoddesc}
-
-\begin{methoddesc}{log_request}{\optional{code\optional{, size}}}
-Logs an accepted (successful) request. \var{code} should specify
-the numeric HTTP code associated with the response. If a size of
-the response is available, then it should be passed as the
-\var{size} parameter.
-\end{methoddesc}
-
-\begin{methoddesc}{log_error}{...}
-Logs an error when a request cannot be fulfilled. By default,
-it passes the message to \method{log_message()}, so it takes the
-same arguments (\var{format} and additional values).
-\end{methoddesc}
-
-\begin{methoddesc}{log_message}{format, ...}
-Logs an arbitrary message to \code{sys.stderr}. This is typically
-overridden to create custom error logging mechanisms. The
-\var{format} argument is a standard printf-style format string,
-where the additional arguments to \method{log_message()} are applied
-as inputs to the formatting. The client address and current date
-and time are prefixed to every message logged.
-\end{methoddesc}
-
-\begin{methoddesc}{version_string}{}
-Returns the server software's version string. This is a combination
-of the \member{server_version} and \member{sys_version} class variables.
-\end{methoddesc}
-
-\begin{methoddesc}{date_time_string}{}
-Returns the current date and time, formatted for a message header.
-\end{methoddesc}
-
-\begin{methoddesc}{log_data_time_string}{}
-Returns the current date and time, formatted for logging.
-\end{methoddesc}
-
-\begin{methoddesc}{address_string}{}
-Returns the client address, formatted for logging. A name lookup
-is performed on the client's IP address.
-\end{methoddesc}
-
-
-\begin{seealso}
- \seemodule{CGIHTTPServer}{Extended request handler that supports CGI
- scripts.}
-
- \seemodule{SimpleHTTPServer}{Basic request handler that limits response
- to files actually under the document root.}
-\end{seealso}
diff --git a/Doc/lib/libbastion.tex b/Doc/lib/libbastion.tex
deleted file mode 100644
index 9f45c47a2c..0000000000
--- a/Doc/lib/libbastion.tex
+++ /dev/null
@@ -1,57 +0,0 @@
-\section{\module{Bastion} ---
- Restricting access to objects}
-
-\declaremodule{standard}{Bastion}
-\modulesynopsis{Providing restricted access to objects.}
-\moduleauthor{Barry Warsaw}{bwarsaw@python.org}
-\versionchanged[Disabled module]{2.3}
-
-\begin{notice}[warning]
- The documentation has been left in place to help in reading old code
- that uses the module.
-\end{notice}
-
-% I'm concerned that the word 'bastion' won't be understood by people
-% for whom English is a second language, making the module name
-% somewhat mysterious. Thus, the brief definition... --amk
-
-According to the dictionary, a bastion is ``a fortified area or
-position'', or ``something that is considered a stronghold.'' It's a
-suitable name for this module, which provides a way to forbid access
-to certain attributes of an object. It must always be used with the
-\refmodule{rexec} module, in order to allow restricted-mode programs
-access to certain safe attributes of an object, while denying access
-to other, unsafe attributes.
-
-% I've punted on the issue of documenting keyword arguments for now.
-
-\begin{funcdesc}{Bastion}{object\optional{, filter\optional{,
- name\optional{, class}}}}
-Protect the object \var{object}, returning a bastion for the
-object. Any attempt to access one of the object's attributes will
-have to be approved by the \var{filter} function; if the access is
-denied an \exception{AttributeError} exception will be raised.
-
-If present, \var{filter} must be a function that accepts a string
-containing an attribute name, and returns true if access to that
-attribute will be permitted; if \var{filter} returns false, the access
-is denied. The default filter denies access to any function beginning
-with an underscore (\character{_}). The bastion's string representation
-will be \samp{} if a value for
-\var{name} is provided; otherwise, \samp{repr(\var{object})} will be
-used.
-
-\var{class}, if present, should be a subclass of \class{BastionClass};
-see the code in \file{bastion.py} for the details. Overriding the
-default \class{BastionClass} will rarely be required.
-\end{funcdesc}
-
-
-\begin{classdesc}{BastionClass}{getfunc, name}
-Class which actually implements bastion objects. This is the default
-class used by \function{Bastion()}. The \var{getfunc} parameter is a
-function which returns the value of an attribute which should be
-exposed to the restricted execution environment when called with the
-name of the attribute as the only parameter. \var{name} is used to
-construct the \function{repr()} of the \class{BastionClass} instance.
-\end{classdesc}
diff --git a/Doc/lib/libbinascii.tex b/Doc/lib/libbinascii.tex
deleted file mode 100644
index 9850418fef..0000000000
--- a/Doc/lib/libbinascii.tex
+++ /dev/null
@@ -1,143 +0,0 @@
-\section{\module{binascii} ---
- Convert between binary and \ASCII}
-
-\declaremodule{builtin}{binascii}
-\modulesynopsis{Tools for converting between binary and various
- \ASCII-encoded binary representations.}
-
-
-The \module{binascii} module contains a number of methods to convert
-between binary and various \ASCII-encoded binary
-representations. Normally, you will not use these functions directly
-but use wrapper modules like \refmodule{uu}\refstmodindex{uu} or
-\refmodule{binhex}\refstmodindex{binhex} instead, this module solely
-exists because bit-manipulation of large amounts of data is slow in
-Python.
-
-The \module{binascii} module defines the following functions:
-
-\begin{funcdesc}{a2b_uu}{string}
-Convert a single line of uuencoded data back to binary and return the
-binary data. Lines normally contain 45 (binary) bytes, except for the
-last line. Line data may be followed by whitespace.
-\end{funcdesc}
-
-\begin{funcdesc}{b2a_uu}{data}
-Convert binary data to a line of \ASCII{} characters, the return value
-is the converted line, including a newline char. The length of
-\var{data} should be at most 45.
-\end{funcdesc}
-
-\begin{funcdesc}{a2b_base64}{string}
-Convert a block of base64 data back to binary and return the
-binary data. More than one line may be passed at a time.
-\end{funcdesc}
-
-\begin{funcdesc}{b2a_base64}{data}
-Convert binary data to a line of \ASCII{} characters in base64 coding.
-The return value is the converted line, including a newline char.
-The length of \var{data} should be at most 57 to adhere to the base64
-standard.
-\end{funcdesc}
-
-\begin{funcdesc}{a2b_qp}{string\optional{, header}}
-Convert a block of quoted-printable data back to binary and return the
-binary data. More than one line may be passed at a time.
-If the optional argument \var{header} is present and true, underscores
-will be decoded as spaces.
-\end{funcdesc}
-
-\begin{funcdesc}{b2a_qp}{data\optional{, quotetabs, istext, header}}
-Convert binary data to a line(s) of \ASCII{} characters in
-quoted-printable encoding. The return value is the converted line(s).
-If the optional argument \var{quotetabs} is present and true, all tabs
-and spaces will be encoded. If the optional argument \var{header} is
-present and true, spaces will be encoded as underscores per RFC1522.
-If the optional argument \var{header} is present and false, newline
-characters will be encoded as well, otherwise linefeed conversion might
-corrupt the binary data stream.
-\end{funcdesc}
-
-\begin{funcdesc}{a2b_hqx}{string}
-Convert binhex4 formatted \ASCII{} data to binary, without doing
-RLE-decompression. The string should contain a complete number of
-binary bytes, or (in case of the last portion of the binhex4 data)
-have the remaining bits zero.
-\end{funcdesc}
-
-\begin{funcdesc}{rledecode_hqx}{data}
-Perform RLE-decompression on the data, as per the binhex4
-standard. The algorithm uses \code{0x90} after a byte as a repeat
-indicator, followed by a count. A count of \code{0} specifies a byte
-value of \code{0x90}. The routine returns the decompressed data,
-unless data input data ends in an orphaned repeat indicator, in which
-case the \exception{Incomplete} exception is raised.
-\end{funcdesc}
-
-\begin{funcdesc}{rlecode_hqx}{data}
-Perform binhex4 style RLE-compression on \var{data} and return the
-result.
-\end{funcdesc}
-
-\begin{funcdesc}{b2a_hqx}{data}
-Perform hexbin4 binary-to-\ASCII{} translation and return the
-resulting string. The argument should already be RLE-coded, and have a
-length divisible by 3 (except possibly the last fragment).
-\end{funcdesc}
-
-\begin{funcdesc}{crc_hqx}{data, crc}
-Compute the binhex4 crc value of \var{data}, starting with an initial
-\var{crc} and returning the result.
-\end{funcdesc}
-
-\begin{funcdesc}{crc32}{data\optional{, crc}}
-Compute CRC-32, the 32-bit checksum of data, starting with an initial
-crc. This is consistent with the ZIP file checksum. Since the
-algorithm is designed for use as a checksum algorithm, it is not
-suitable for use as a general hash algorithm. Use as follows:
-\begin{verbatim}
- print binascii.crc32("hello world")
- # Or, in two pieces:
- crc = binascii.crc32("hello")
- crc = binascii.crc32(" world", crc)
- print crc
-\end{verbatim}
-\end{funcdesc}
-
-\begin{funcdesc}{b2a_hex}{data}
-\funcline{hexlify}{data}
-Return the hexadecimal representation of the binary \var{data}. Every
-byte of \var{data} is converted into the corresponding 2-digit hex
-representation. The resulting string is therefore twice as long as
-the length of \var{data}.
-\end{funcdesc}
-
-\begin{funcdesc}{a2b_hex}{hexstr}
-\funcline{unhexlify}{hexstr}
-Return the binary data represented by the hexadecimal string
-\var{hexstr}. This function is the inverse of \function{b2a_hex()}.
-\var{hexstr} must contain an even number of hexadecimal digits (which
-can be upper or lower case), otherwise a \exception{TypeError} is
-raised.
-\end{funcdesc}
-
-\begin{excdesc}{Error}
-Exception raised on errors. These are usually programming errors.
-\end{excdesc}
-
-\begin{excdesc}{Incomplete}
-Exception raised on incomplete data. These are usually not programming
-errors, but may be handled by reading a little more data and trying
-again.
-\end{excdesc}
-
-
-\begin{seealso}
- \seemodule{base64}{Support for base64 encoding used in MIME email messages.}
-
- \seemodule{binhex}{Support for the binhex format used on the Macintosh.}
-
- \seemodule{uu}{Support for UU encoding used on \UNIX.}
-
- \seemodule{quopri}{Support for quoted-printable encoding used in MIME email messages. }
-\end{seealso}
diff --git a/Doc/lib/libbinhex.tex b/Doc/lib/libbinhex.tex
deleted file mode 100644
index d30f2b437c..0000000000
--- a/Doc/lib/libbinhex.tex
+++ /dev/null
@@ -1,55 +0,0 @@
-\section{\module{binhex} ---
- Encode and decode binhex4 files}
-
-\declaremodule{standard}{binhex}
-\modulesynopsis{Encode and decode files in binhex4 format.}
-
-
-This module encodes and decodes files in binhex4 format, a format
-allowing representation of Macintosh files in \ASCII. On the Macintosh,
-both forks of a file and the finder information are encoded (or
-decoded), on other platforms only the data fork is handled.
-
-The \module{binhex} module defines the following functions:
-
-\begin{funcdesc}{binhex}{input, output}
-Convert a binary file with filename \var{input} to binhex file
-\var{output}. The \var{output} parameter can either be a filename or a
-file-like object (any object supporting a \method{write()} and
-\method{close()} method).
-\end{funcdesc}
-
-\begin{funcdesc}{hexbin}{input\optional{, output}}
-Decode a binhex file \var{input}. \var{input} may be a filename or a
-file-like object supporting \method{read()} and \method{close()} methods.
-The resulting file is written to a file named \var{output}, unless the
-argument is omitted in which case the output filename is read from the
-binhex file.
-\end{funcdesc}
-
-The following exception is also defined:
-
-\begin{excdesc}{Error}
-Exception raised when something can't be encoded using the binhex
-format (for example, a filename is too long to fit in the filename
-field), or when input is not properly encoded binhex data.
-\end{excdesc}
-
-
-\begin{seealso}
- \seemodule{binascii}{Support module containing \ASCII-to-binary
- and binary-to-\ASCII{} conversions.}
-\end{seealso}
-
-
-\subsection{Notes \label{binhex-notes}}
-
-There is an alternative, more powerful interface to the coder and
-decoder, see the source for details.
-
-If you code or decode textfiles on non-Macintosh platforms they will
-still use the Macintosh newline convention (carriage-return as end of
-line).
-
-As of this writing, \function{hexbin()} appears to not work in all
-cases.
diff --git a/Doc/lib/libbisect.tex b/Doc/lib/libbisect.tex
deleted file mode 100644
index 32418914b8..0000000000
--- a/Doc/lib/libbisect.tex
+++ /dev/null
@@ -1,101 +0,0 @@
-\section{\module{bisect} ---
- Array bisection algorithm}
-
-\declaremodule{standard}{bisect}
-\modulesynopsis{Array bisection algorithms for binary searching.}
-\sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org}
-% LaTeX produced by Fred L. Drake, Jr. , with an
-% example based on the PyModules FAQ entry by Aaron Watters
-% .
-
-
-This module provides support for maintaining a list in sorted order
-without having to sort the list after each insertion. For long lists
-of items with expensive comparison operations, this can be an
-improvement over the more common approach. The module is called
-\module{bisect} because it uses a basic bisection algorithm to do its
-work. The source code may be most useful as a working example of the
-algorithm (the boundary conditions are already right!).
-
-The following functions are provided:
-
-\begin{funcdesc}{bisect_left}{list, item\optional{, lo\optional{, hi}}}
- Locate the proper insertion point for \var{item} in \var{list} to
- maintain sorted order. The parameters \var{lo} and \var{hi} may be
- used to specify a subset of the list which should be considered; by
- default the entire list is used. If \var{item} is already present
- in \var{list}, the insertion point will be before (to the left of)
- any existing entries. The return value is suitable for use as the
- first parameter to \code{\var{list}.insert()}. This assumes that
- \var{list} is already sorted.
-\versionadded{2.1}
-\end{funcdesc}
-
-\begin{funcdesc}{bisect_right}{list, item\optional{, lo\optional{, hi}}}
- Similar to \function{bisect_left()}, but returns an insertion point
- which comes after (to the right of) any existing entries of
- \var{item} in \var{list}.
-\versionadded{2.1}
-\end{funcdesc}
-
-\begin{funcdesc}{bisect}{\unspecified}
- Alias for \function{bisect_right()}.
-\end{funcdesc}
-
-\begin{funcdesc}{insort_left}{list, item\optional{, lo\optional{, hi}}}
- Insert \var{item} in \var{list} in sorted order. This is equivalent
- to \code{\var{list}.insert(bisect.bisect_left(\var{list}, \var{item},
- \var{lo}, \var{hi}), \var{item})}. This assumes that \var{list} is
- already sorted.
-\versionadded{2.1}
-\end{funcdesc}
-
-\begin{funcdesc}{insort_right}{list, item\optional{, lo\optional{, hi}}}
- Similar to \function{insort_left()}, but inserting \var{item} in
- \var{list} after any existing entries of \var{item}.
-\versionadded{2.1}
-\end{funcdesc}
-
-\begin{funcdesc}{insort}{\unspecified}
- Alias for \function{insort_right()}.
-\end{funcdesc}
-
-
-\subsection{Examples}
-\nodename{bisect-example}
-
-The \function{bisect()} function is generally useful for categorizing
-numeric data. This example uses \function{bisect()} to look up a
-letter grade for an exam total (say) based on a set of ordered numeric
-breakpoints: 85 and up is an `A', 75..84 is a `B', etc.
-
-\begin{verbatim}
->>> grades = "FEDCBA"
->>> breakpoints = [30, 44, 66, 75, 85]
->>> from bisect import bisect
->>> def grade(total):
-... return grades[bisect(breakpoints, total)]
-...
->>> grade(66)
-'C'
->>> map(grade, [33, 99, 77, 44, 12, 88])
-['E', 'A', 'B', 'D', 'F', 'A']
-\end{verbatim}
-
-The bisect module can be used with the Queue module to implement a priority
-queue (example courtesy of Fredrik Lundh): \index{Priority Queue}
-
-\begin{verbatim}
-import Queue, bisect
-
-class PriorityQueue(Queue.Queue):
- def _put(self, item):
- bisect.insort(self.queue, item)
-
-# usage
-queue = PriorityQueue(0)
-queue.put((2, "second"))
-queue.put((1, "first"))
-queue.put((3, "third"))
-priority, value = queue.get()
-\end{verbatim}
diff --git a/Doc/lib/libbltin.tex b/Doc/lib/libbltin.tex
deleted file mode 100644
index 5cc7626fa9..0000000000
--- a/Doc/lib/libbltin.tex
+++ /dev/null
@@ -1,11 +0,0 @@
-\section{\module{__builtin__} ---
- Built-in functions}
-
-\declaremodule[builtin]{builtin}{__builtin__}
-\modulesynopsis{The set of built-in functions.}
-
-
-This module provides direct access to all `built-in' identifiers of
-Python; e.g. \code{__builtin__.open} is the full name for the built-in
-function \function{open()}. See section \ref{built-in-funcs}, ``Built-in
-Functions.''
diff --git a/Doc/lib/libbsddb.tex b/Doc/lib/libbsddb.tex
deleted file mode 100644
index 7fb8f76e01..0000000000
--- a/Doc/lib/libbsddb.tex
+++ /dev/null
@@ -1,182 +0,0 @@
-\section{\module{bsddb} ---
- Interface to Berkeley DB library}
-
-\declaremodule{extension}{bsddb}
- \platform{Unix, Windows}
-\modulesynopsis{Interface to Berkeley DB database library}
-\sectionauthor{Skip Montanaro}{skip@mojam.com}
-
-
-The \module{bsddb} module provides an interface to the Berkeley DB
-library. Users can create hash, btree or record based library files
-using the appropriate open call. Bsddb objects behave generally like
-dictionaries. Keys and values must be strings, however, so to use
-other objects as keys or to store other kinds of objects the user must
-serialize them somehow, typically using marshal.dumps or pickle.dumps.
-
-Starting with Python 2.3 the \module{bsddb} module requires the
-Berkeley DB library version 3.1 or later (it is known to work with 3.1
-thru 4.1 at the time of this writing).
-
-\begin{seealso}
- \seeurl{http://pybsddb.sourceforge.net/}{Website with documentation
- for the new python Berkeley DB interface that closely mirrors the
- sleepycat object oriented interface provided in Berkeley DB 3 and 4.}
- \seeurl{http://www.sleepycat.com/}{Sleepycat Software produces the
- modern Berkeley DB library.}
-\end{seealso}
-
-The following is a description of the legacy \module{bsddb} interface
-compatible with the old python bsddb module. For details about the more
-modern Db and DbEnv object oriented interface see the above mentioned
-pybsddb URL.
-
-The \module{bsddb} module defines the following functions that create
-objects that access the appropriate type of Berkeley DB file. The
-first two arguments of each function are the same. For ease of
-portability, only the first two arguments should be used in most
-instances.
-
-\begin{funcdesc}{hashopen}{filename\optional{, flag\optional{,
- mode\optional{, bsize\optional{,
- ffactor\optional{, nelem\optional{,
- cachesize\optional{, hash\optional{,
- lorder}}}}}}}}}
-Open the hash format file named \var{filename}. Files never intended
-to be preserved on disk may be created by passing \code{None} as the
-\var{filename}. The optional
-\var{flag} identifies the mode used to open the file. It may be
-\character{r} (read only, default), \character{w} (read-write) ,
-\character{c} (read-write - create if necessary) or
-\character{n} (read-write - truncate to zero length). The other
-arguments are rarely used and are just passed to the low-level
-\cfunction{dbopen()} function. Consult the Berkeley DB documentation
-for their use and interpretation.
-\end{funcdesc}
-
-\begin{funcdesc}{btopen}{filename\optional{, flag\optional{,
-mode\optional{, btflags\optional{, cachesize\optional{, maxkeypage\optional{,
-minkeypage\optional{, psize\optional{, lorder}}}}}}}}}
-
-Open the btree format file named \var{filename}. Files never intended
-to be preserved on disk may be created by passing \code{None} as the
-\var{filename}. The optional
-\var{flag} identifies the mode used to open the file. It may be
-\character{r} (read only, default), \character{w} (read-write),
-\character{c} (read-write - create if necessary) or
-\character{n} (read-write - truncate to zero length). The other
-arguments are rarely used and are just passed to the low-level dbopen
-function. Consult the Berkeley DB documentation for their use and
-interpretation.
-\end{funcdesc}
-
-\begin{funcdesc}{rnopen}{filename\optional{, flag\optional{, mode\optional{,
-rnflags\optional{, cachesize\optional{, psize\optional{, lorder\optional{,
-reclen\optional{, bval\optional{, bfname}}}}}}}}}}
-
-Open a DB record format file named \var{filename}. Files never intended
-to be preserved on disk may be created by passing \code{None} as the
-\var{filename}. The optional
-\var{flag} identifies the mode used to open the file. It may be
-\character{r} (read only, default), \character{w} (read-write),
-\character{c} (read-write - create if necessary) or
-\character{n} (read-write - truncate to zero length). The other
-arguments are rarely used and are just passed to the low-level dbopen
-function. Consult the Berkeley DB documentation for their use and
-interpretation.
-\end{funcdesc}
-
-
-\begin{seealso}
- \seemodule{dbhash}{DBM-style interface to the \module{bsddb}}
-\end{seealso}
-
-\begin{notice}
-Beginning in 2.3 some Unix versions of Python may have a \module{bsddb185}
-module. This is present \emph{only} to allow backwards compatibility with
-systems which ship with the old Berkeley DB 1.85 database library. The
-\module{bsddb185} module should never be used directly in new code.
-\end{notice}
-
-\subsection{Hash, BTree and Record Objects \label{bsddb-objects}}
-
-Once instantiated, hash, btree and record objects support the following
-methods:
-
-\begin{methoddesc}{close}{}
-Close the underlying file. The object can no longer be accessed. Since
-there is no open \method{open} method for these objects, to open the file
-again a new \module{bsddb} module open function must be called.
-\end{methoddesc}
-
-\begin{methoddesc}{keys}{}
-Return the list of keys contained in the DB file. The order of the list is
-unspecified and should not be relied on. In particular, the order of the
-list returned is different for different file formats.
-\end{methoddesc}
-
-\begin{methoddesc}{has_key}{key}
-Return \code{1} if the DB file contains the argument as a key.
-\end{methoddesc}
-
-\begin{methoddesc}{set_location}{key}
-Set the cursor to the item indicated by \var{key} and return a tuple
-containing the key and its value. For binary tree databases (opened
-using \function{btopen()}), if \var{key} does not actually exist in
-the database, the cursor will point to the next item in sorted order
-and return that key and value. For other databases,
-\exception{KeyError} will be raised if \var{key} is not found in the
-database.
-\end{methoddesc}
-
-\begin{methoddesc}{first}{}
-Set the cursor to the first item in the DB file and return it. The order of
-keys in the file is unspecified, except in the case of B-Tree databases.
-\end{methoddesc}
-
-\begin{methoddesc}{next}{}
-Set the cursor to the next item in the DB file and return it. The order of
-keys in the file is unspecified, except in the case of B-Tree databases.
-\end{methoddesc}
-
-\begin{methoddesc}{previous}{}
-Set the cursor to the previous item in the DB file and return it. The
-order of keys in the file is unspecified, except in the case of B-Tree
-databases. This is not supported on hashtable databases (those opened
-with \function{hashopen()}).
-\end{methoddesc}
-
-\begin{methoddesc}{last}{}
-Set the cursor to the last item in the DB file and return it. The
-order of keys in the file is unspecified. This is not supported on
-hashtable databases (those opened with \function{hashopen()}).
-\end{methoddesc}
-
-\begin{methoddesc}{sync}{}
-Synchronize the database on disk.
-\end{methoddesc}
-
-Example:
-
-\begin{verbatim}
->>> import bsddb
->>> db = bsddb.btopen('/tmp/spam.db', 'c')
->>> for i in range(10): db['%d'%i] = '%d'% (i*i)
-...
->>> db['3']
-'9'
->>> db.keys()
-['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
->>> db.first()
-('0', '0')
->>> db.next()
-('1', '1')
->>> db.last()
-('9', '81')
->>> db.set_location('2')
-('2', '4')
->>> db.previous()
-('1', '1')
->>> db.sync()
-0
-\end{verbatim}
diff --git a/Doc/lib/libbz2.tex b/Doc/lib/libbz2.tex
deleted file mode 100644
index 439f2ba337..0000000000
--- a/Doc/lib/libbz2.tex
+++ /dev/null
@@ -1,174 +0,0 @@
-\section{\module{bz2} ---
- Compression compatible with \program{bzip2}}
-
-\declaremodule{builtin}{bz2}
-\modulesynopsis{Interface to compression and decompression
- routines compatible with \program{bzip2}.}
-\moduleauthor{Gustavo Niemeyer}{niemeyer@conectiva.com}
-\sectionauthor{Gustavo Niemeyer}{niemeyer@conectiva.com}
-
-\versionadded{2.3}
-
-This module provides a comprehensive interface for the bz2 compression library.
-It implements a complete file interface, one-shot (de)compression functions,
-and types for sequential (de)compression.
-
-Here is a resume of the features offered by the bz2 module:
-
-\begin{itemize}
-\item \class{BZ2File} class implements a complete file interface, including
- \method{readline()}, \method{readlines()},
- \method{writelines()}, \method{seek()}, etc;
-\item \class{BZ2File} class implements emulated \method{seek()} support;
-\item \class{BZ2File} class implements universal newline support;
-\item \class{BZ2File} class offers an optimized line iteration using
- the readahead algorithm borrowed from file objects;
-\item Sequential (de)compression supported by \class{BZ2Compressor} and
- \class{BZ2Decompressor} classes;
-\item One-shot (de)compression supported by \function{compress()} and
- \function{decompress()} functions;
-\item Thread safety uses individual locking mechanism;
-\item Complete inline documentation;
-\end{itemize}
-
-
-\subsection{(De)compression of files}
-
-Handling of compressed files is offered by the \class{BZ2File} class.
-
-\begin{classdesc}{BZ2File}{filename\optional{, mode\optional{,
- buffering\optional{, compresslevel}}}}
-Open a bz2 file. Mode can be either \code{'r'} or \code{'w'}, for reading
-(default) or writing. When opened for writing, the file will be created if
-it doesn't exist, and truncated otherwise. If \var{buffering} is given,
-\code{0} means unbuffered, and larger numbers specify the buffer size;
-the default is \code{0}. If
-\var{compresslevel} is given, it must be a number between \code{1} and
-\code{9}; the default is \code{9}.
-Add a \character{U} to mode to open the file for input with universal newline
-support. Any line ending in the input file will be seen as a
-\character{\e n} in Python. Also, a file so opened gains the
-attribute \member{newlines}; the value for this attribute is one of
-\code{None} (no newline read yet), \code{'\e r'}, \code{'\e n'},
-\code{'\e r\e n'} or a tuple containing all the newline types
-seen. Universal newlines are available only when reading.
-Instances support iteration in the same way as normal \class{file}
-instances.
-\end{classdesc}
-
-\begin{methoddesc}[BZ2File]{close}{}
-Close the file. Sets data attribute \member{closed} to true. A closed file
-cannot be used for further I/O operations. \method{close()} may be called
-more than once without error.
-\end{methoddesc}
-
-\begin{methoddesc}[BZ2File]{read}{\optional{size}}
-Read at most \var{size} uncompressed bytes, returned as a string. If the
-\var{size} argument is negative or omitted, read until EOF is reached.
-\end{methoddesc}
-
-\begin{methoddesc}[BZ2File]{readline}{\optional{size}}
-Return the next line from the file, as a string, retaining newline.
-A non-negative \var{size} argument limits the maximum number of bytes to
-return (an incomplete line may be returned then). Return an empty
-string at EOF.
-\end{methoddesc}
-
-\begin{methoddesc}[BZ2File]{readlines}{\optional{size}}
-Return a list of lines read. The optional \var{size} argument, if given,
-is an approximate bound on the total number of bytes in the lines returned.
-\end{methoddesc}
-
-\begin{methoddesc}[BZ2File]{xreadlines}{}
-For backward compatibility. \class{BZ2File} objects now include the
-performance optimizations previously implemented in the
-\refmodule{xreadlines} module.
-\deprecated{2.3}{This exists only for compatibility with the method by
- this name on \class{file} objects, which is
- deprecated. Use \code{for line in file} instead.}
-\end{methoddesc}
-
-\begin{methoddesc}[BZ2File]{seek}{offset\optional{, whence}}
-Move to new file position. Argument \var{offset} is a byte count. Optional
-argument \var{whence} defaults to \code{0} (offset from start of file,
-offset should be \code{>= 0}); other values are \code{1} (move relative to
-current position, positive or negative), and \code{2} (move relative to end
-of file, usually negative, although many platforms allow seeking beyond
-the end of a file).
-
-Note that seeking of bz2 files is emulated, and depending on the parameters
-the operation may be extremely slow.
-\end{methoddesc}
-
-\begin{methoddesc}[BZ2File]{tell}{}
-Return the current file position, an integer (may be a long integer).
-\end{methoddesc}
-
-\begin{methoddesc}[BZ2File]{write}{data}
-Write string \var{data} to file. Note that due to buffering, \method{close()}
-may be needed before the file on disk reflects the data written.
-\end{methoddesc}
-
-\begin{methoddesc}[BZ2File]{writelines}{sequence_of_strings}
-Write the sequence of strings to the file. Note that newlines are not added.
-The sequence can be any iterable object producing strings. This is equivalent
-to calling write() for each string.
-\end{methoddesc}
-
-
-\subsection{Sequential (de)compression}
-
-Sequential compression and decompression is done using the classes
-\class{BZ2Compressor} and \class{BZ2Decompressor}.
-
-\begin{classdesc}{BZ2Compressor}{\optional{compresslevel}}
-Create a new compressor object. This object may be used to compress
-data sequentially. If you want to compress data in one shot, use the
-\function{compress()} function instead. The \var{compresslevel} parameter,
-if given, must be a number between \code{1} and \code{9}; the default
-is \code{9}.
-\end{classdesc}
-
-\begin{methoddesc}[BZ2Compressor]{compress}{data}
-Provide more data to the compressor object. It will return chunks of compressed
-data whenever possible. When you've finished providing data to compress, call
-the \method{flush()} method to finish the compression process, and return what
-is left in internal buffers.
-\end{methoddesc}
-
-\begin{methoddesc}[BZ2Compressor]{flush}{}
-Finish the compression process and return what is left in internal buffers. You
-must not use the compressor object after calling this method.
-\end{methoddesc}
-
-\begin{classdesc}{BZ2Decompressor}{}
-Create a new decompressor object. This object may be used to decompress
-data sequentially. If you want to decompress data in one shot, use the
-\function{decompress()} function instead.
-\end{classdesc}
-
-\begin{methoddesc}[BZ2Decompressor]{decompress}{data}
-Provide more data to the decompressor object. It will return chunks of
-decompressed data whenever possible. If you try to decompress data after the
-end of stream is found, \exception{EOFError} will be raised. If any data was
-found after the end of stream, it'll be ignored and saved in
-\member{unused\_data} attribute.
-\end{methoddesc}
-
-
-\subsection{One-shot (de)compression}
-
-One-shot compression and decompression is provided through the
-\function{compress()} and \function{decompress()} functions.
-
-\begin{funcdesc}{compress}{data\optional{, compresslevel}}
-Compress \var{data} in one shot. If you want to compress data sequentially,
-use an instance of \class{BZ2Compressor} instead. The \var{compresslevel}
-parameter, if given, must be a number between \code{1} and \code{9};
-the default is \code{9}.
-\end{funcdesc}
-
-\begin{funcdesc}{decompress}{data}
-Decompress \var{data} in one shot. If you want to decompress data
-sequentially, use an instance of \class{BZ2Decompressor} instead.
-\end{funcdesc}
diff --git a/Doc/lib/libcalendar.tex b/Doc/lib/libcalendar.tex
deleted file mode 100644
index bf0c85bc2c..0000000000
--- a/Doc/lib/libcalendar.tex
+++ /dev/null
@@ -1,112 +0,0 @@
-\section{\module{calendar} ---
- General calendar-related functions}
-
-\declaremodule{standard}{calendar}
-\modulesynopsis{Functions for working with calendars,
- including some emulation of the \UNIX\ \program{cal}
- program.}
-\sectionauthor{Drew Csillag}{drew_csillag@geocities.com}
-
-This module allows you to output calendars like the \UNIX{}
-\program{cal} program, and provides additional useful functions
-related to the calendar. By default, these calendars have Monday as
-the first day of the week, and Sunday as the last (the European
-convention). Use \function{setfirstweekday()} to set the first day of the
-week to Sunday (6) or to any other weekday. Parameters that specify
-dates are given as integers.
-
-Most of these functions rely on the \module{datetime} module which
-uses an idealized calendar, the current Gregorian calendar indefinitely
-extended in both directions. This matches the definition of the
-"proleptic Gregorian" calendar in Dershowitz and Reingold's book
-"Calendrical Calculations", where it's the base calendar for all
-computations.
-
-\begin{funcdesc}{setfirstweekday}{weekday}
-Sets the weekday (\code{0} is Monday, \code{6} is Sunday) to start
-each week. The values \constant{MONDAY}, \constant{TUESDAY},
-\constant{WEDNESDAY}, \constant{THURSDAY}, \constant{FRIDAY},
-\constant{SATURDAY}, and \constant{SUNDAY} are provided for
-convenience. For example, to set the first weekday to Sunday:
-
-\begin{verbatim}
-import calendar
-calendar.setfirstweekday(calendar.SUNDAY)
-\end{verbatim}
-\versionadded{2.0}
-\end{funcdesc}
-
-\begin{funcdesc}{firstweekday}{}
-Returns the current setting for the weekday to start each week.
-\versionadded{2.0}
-\end{funcdesc}
-
-\begin{funcdesc}{isleap}{year}
-Returns \code{1} if \var{year} is a leap year, otherwise \code{0}.
-\end{funcdesc}
-
-\begin{funcdesc}{leapdays}{y1, y2}
-Returns the number of leap years in the range
-[\var{y1}\ldots\var{y2}), where \var{y1} and \var{y2} are years.
-\versionchanged[This function didn't work for ranges spanning
- a century change in Python 1.5.2]{2.0}
-\end{funcdesc}
-
-\begin{funcdesc}{weekday}{year, month, day}
-Returns the day of the week (\code{0} is Monday) for \var{year}
-(\code{1970}--\ldots), \var{month} (\code{1}--\code{12}), \var{day}
-(\code{1}--\code{31}).
-\end{funcdesc}
-
-\begin{funcdesc}{monthrange}{year, month}
-Returns weekday of first day of the month and number of days in month,
-for the specified \var{year} and \var{month}.
-\end{funcdesc}
-
-\begin{funcdesc}{monthcalendar}{year, month}
-Returns a matrix representing a month's calendar. Each row represents
-a week; days outside of the month a represented by zeros.
-Each week begins with Monday unless set by \function{setfirstweekday()}.
-\end{funcdesc}
-
-\begin{funcdesc}{prmonth}{theyear, themonth\optional{, w\optional{, l}}}
-Prints a month's calendar as returned by \function{month()}.
-\end{funcdesc}
-
-\begin{funcdesc}{month}{theyear, themonth\optional{, w\optional{, l}}}
-Returns a month's calendar in a multi-line string. If \var{w} is
-provided, it specifies the width of the date columns, which are
-centered. If \var{l} is given, it specifies the number of lines that
-each week will use. Depends on the first weekday as set by
-\function{setfirstweekday()}.
-\versionadded{2.0}
-\end{funcdesc}
-
-\begin{funcdesc}{prcal}{year\optional{, w\optional{, l\optional{c}}}}
-Prints the calendar for an entire year as returned by
-\function{calendar()}.
-\end{funcdesc}
-
-\begin{funcdesc}{calendar}{year\optional{, w\optional{, l\optional{c}}}}
-Returns a 3-column calendar for an entire year as a multi-line string.
-Optional parameters \var{w}, \var{l}, and \var{c} are for date column
-width, lines per week, and number of spaces between month columns,
-respectively. Depends on the first weekday as set by
-\function{setfirstweekday()}. The earliest year for which a calendar can
-be generated is platform-dependent.
-\versionadded{2.0}
-\end{funcdesc}
-
-\begin{funcdesc}{timegm}{tuple}
-An unrelated but handy function that takes a time tuple such as
-returned by the \function{gmtime()} function in the \refmodule{time}
-module, and returns the corresponding \UNIX{} timestamp value, assuming
-an epoch of 1970, and the POSIX encoding. In fact,
-\function{time.gmtime()} and \function{timegm()} are each others' inverse.
-\versionadded{2.0}
-\end{funcdesc}
-
-
-\begin{seealso}
- \seemodule{time}{Low-level time related functions.}
-\end{seealso}
diff --git a/Doc/lib/libcd.tex b/Doc/lib/libcd.tex
deleted file mode 100644
index 0e7f90c2ac..0000000000
--- a/Doc/lib/libcd.tex
+++ /dev/null
@@ -1,304 +0,0 @@
-\section{\module{cd} ---
- CD-ROM access on SGI systems}
-
-\declaremodule{builtin}{cd}
- \platform{IRIX}
-\modulesynopsis{Interface to the CD-ROM on Silicon Graphics systems.}
-
-
-This module provides an interface to the Silicon Graphics CD library.
-It is available only on Silicon Graphics systems.
-
-The way the library works is as follows. A program opens the CD-ROM
-device with \function{open()} and creates a parser to parse the data
-from the CD with \function{createparser()}. The object returned by
-\function{open()} can be used to read data from the CD, but also to get
-status information for the CD-ROM device, and to get information about
-the CD, such as the table of contents. Data from the CD is passed to
-the parser, which parses the frames, and calls any callback
-functions that have previously been added.
-
-An audio CD is divided into \dfn{tracks} or \dfn{programs} (the terms
-are used interchangeably). Tracks can be subdivided into
-\dfn{indices}. An audio CD contains a \dfn{table of contents} which
-gives the starts of the tracks on the CD. Index 0 is usually the
-pause before the start of a track. The start of the track as given by
-the table of contents is normally the start of index 1.
-
-Positions on a CD can be represented in two ways. Either a frame
-number or a tuple of three values, minutes, seconds and frames. Most
-functions use the latter representation. Positions can be both
-relative to the beginning of the CD, and to the beginning of the
-track.
-
-Module \module{cd} defines the following functions and constants:
-
-
-\begin{funcdesc}{createparser}{}
-Create and return an opaque parser object. The methods of the parser
-object are described below.
-\end{funcdesc}
-
-\begin{funcdesc}{msftoframe}{minutes, seconds, frames}
-Converts a \code{(\var{minutes}, \var{seconds}, \var{frames})} triple
-representing time in absolute time code into the corresponding CD
-frame number.
-\end{funcdesc}
-
-\begin{funcdesc}{open}{\optional{device\optional{, mode}}}
-Open the CD-ROM device. The return value is an opaque player object;
-methods of the player object are described below. The device is the
-name of the SCSI device file, e.g. \code{'/dev/scsi/sc0d4l0'}, or
-\code{None}. If omitted or \code{None}, the hardware inventory is
-consulted to locate a CD-ROM drive. The \var{mode}, if not omited,
-should be the string \code{'r'}.
-\end{funcdesc}
-
-The module defines the following variables:
-
-\begin{excdesc}{error}
-Exception raised on various errors.
-\end{excdesc}
-
-\begin{datadesc}{DATASIZE}
-The size of one frame's worth of audio data. This is the size of the
-audio data as passed to the callback of type \code{audio}.
-\end{datadesc}
-
-\begin{datadesc}{BLOCKSIZE}
-The size of one uninterpreted frame of audio data.
-\end{datadesc}
-
-The following variables are states as returned by
-\function{getstatus()}:
-
-\begin{datadesc}{READY}
-The drive is ready for operation loaded with an audio CD.
-\end{datadesc}
-
-\begin{datadesc}{NODISC}
-The drive does not have a CD loaded.
-\end{datadesc}
-
-\begin{datadesc}{CDROM}
-The drive is loaded with a CD-ROM. Subsequent play or read operations
-will return I/O errors.
-\end{datadesc}
-
-\begin{datadesc}{ERROR}
-An error occurred while trying to read the disc or its table of
-contents.
-\end{datadesc}
-
-\begin{datadesc}{PLAYING}
-The drive is in CD player mode playing an audio CD through its audio
-jacks.
-\end{datadesc}
-
-\begin{datadesc}{PAUSED}
-The drive is in CD layer mode with play paused.
-\end{datadesc}
-
-\begin{datadesc}{STILL}
-The equivalent of \constant{PAUSED} on older (non 3301) model Toshiba
-CD-ROM drives. Such drives have never been shipped by SGI.
-\end{datadesc}
-
-\begin{datadesc}{audio}
-\dataline{pnum}
-\dataline{index}
-\dataline{ptime}
-\dataline{atime}
-\dataline{catalog}
-\dataline{ident}
-\dataline{control}
-Integer constants describing the various types of parser callbacks
-that can be set by the \method{addcallback()} method of CD parser
-objects (see below).
-\end{datadesc}
-
-
-\subsection{Player Objects}
-\label{player-objects}
-
-Player objects (returned by \function{open()}) have the following
-methods:
-
-\begin{methoddesc}[CD player]{allowremoval}{}
-Unlocks the eject button on the CD-ROM drive permitting the user to
-eject the caddy if desired.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{bestreadsize}{}
-Returns the best value to use for the \var{num_frames} parameter of
-the \method{readda()} method. Best is defined as the value that
-permits a continuous flow of data from the CD-ROM drive.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{close}{}
-Frees the resources associated with the player object. After calling
-\method{close()}, the methods of the object should no longer be used.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{eject}{}
-Ejects the caddy from the CD-ROM drive.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{getstatus}{}
-Returns information pertaining to the current state of the CD-ROM
-drive. The returned information is a tuple with the following values:
-\var{state}, \var{track}, \var{rtime}, \var{atime}, \var{ttime},
-\var{first}, \var{last}, \var{scsi_audio}, \var{cur_block}.
-\var{rtime} is the time relative to the start of the current track;
-\var{atime} is the time relative to the beginning of the disc;
-\var{ttime} is the total time on the disc. For more information on
-the meaning of the values, see the man page \manpage{CDgetstatus}{3dm}.
-The value of \var{state} is one of the following: \constant{ERROR},
-\constant{NODISC}, \constant{READY}, \constant{PLAYING},
-\constant{PAUSED}, \constant{STILL}, or \constant{CDROM}.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{gettrackinfo}{track}
-Returns information about the specified track. The returned
-information is a tuple consisting of two elements, the start time of
-the track and the duration of the track.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{msftoblock}{min, sec, frame}
-Converts a minutes, seconds, frames triple representing a time in
-absolute time code into the corresponding logical block number for the
-given CD-ROM drive. You should use \function{msftoframe()} rather than
-\method{msftoblock()} for comparing times. The logical block number
-differs from the frame number by an offset required by certain CD-ROM
-drives.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{play}{start, play}
-Starts playback of an audio CD in the CD-ROM drive at the specified
-track. The audio output appears on the CD-ROM drive's headphone and
-audio jacks (if fitted). Play stops at the end of the disc.
-\var{start} is the number of the track at which to start playing the
-CD; if \var{play} is 0, the CD will be set to an initial paused
-state. The method \method{togglepause()} can then be used to commence
-play.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{playabs}{minutes, seconds, frames, play}
-Like \method{play()}, except that the start is given in minutes,
-seconds, and frames instead of a track number.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{playtrack}{start, play}
-Like \method{play()}, except that playing stops at the end of the
-track.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{playtrackabs}{track, minutes, seconds, frames, play}
-Like \method{play()}, except that playing begins at the specified
-absolute time and ends at the end of the specified track.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{preventremoval}{}
-Locks the eject button on the CD-ROM drive thus preventing the user
-from arbitrarily ejecting the caddy.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{readda}{num_frames}
-Reads the specified number of frames from an audio CD mounted in the
-CD-ROM drive. The return value is a string representing the audio
-frames. This string can be passed unaltered to the
-\method{parseframe()} method of the parser object.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{seek}{minutes, seconds, frames}
-Sets the pointer that indicates the starting point of the next read of
-digital audio data from a CD-ROM. The pointer is set to an absolute
-time code location specified in \var{minutes}, \var{seconds}, and
-\var{frames}. The return value is the logical block number to which
-the pointer has been set.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{seekblock}{block}
-Sets the pointer that indicates the starting point of the next read of
-digital audio data from a CD-ROM. The pointer is set to the specified
-logical block number. The return value is the logical block number to
-which the pointer has been set.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{seektrack}{track}
-Sets the pointer that indicates the starting point of the next read of
-digital audio data from a CD-ROM. The pointer is set to the specified
-track. The return value is the logical block number to which the
-pointer has been set.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{stop}{}
-Stops the current playing operation.
-\end{methoddesc}
-
-\begin{methoddesc}[CD player]{togglepause}{}
-Pauses the CD if it is playing, and makes it play if it is paused.
-\end{methoddesc}
-
-
-\subsection{Parser Objects}
-\label{cd-parser-objects}
-
-Parser objects (returned by \function{createparser()}) have the
-following methods:
-
-\begin{methoddesc}[CD parser]{addcallback}{type, func, arg}
-Adds a callback for the parser. The parser has callbacks for eight
-different types of data in the digital audio data stream. Constants
-for these types are defined at the \module{cd} module level (see above).
-The callback is called as follows: \code{\var{func}(\var{arg}, type,
-data)}, where \var{arg} is the user supplied argument, \var{type} is
-the particular type of callback, and \var{data} is the data returned
-for this \var{type} of callback. The type of the data depends on the
-\var{type} of callback as follows:
-
-\begin{tableii}{l|p{4in}}{code}{Type}{Value}
- \lineii{audio}{String which can be passed unmodified to
-\function{al.writesamps()}.}
- \lineii{pnum}{Integer giving the program (track) number.}
- \lineii{index}{Integer giving the index number.}
- \lineii{ptime}{Tuple consisting of the program time in minutes,
-seconds, and frames.}
- \lineii{atime}{Tuple consisting of the absolute time in minutes,
-seconds, and frames.}
- \lineii{catalog}{String of 13 characters, giving the catalog number
-of the CD.}
- \lineii{ident}{String of 12 characters, giving the ISRC
-identification number of the recording. The string consists of two
-characters country code, three characters owner code, two characters
-giving the year, and five characters giving a serial number.}
- \lineii{control}{Integer giving the control bits from the CD
-subcode data}
-\end{tableii}
-\end{methoddesc}
-
-\begin{methoddesc}[CD parser]{deleteparser}{}
-Deletes the parser and frees the memory it was using. The object
-should not be used after this call. This call is done automatically
-when the last reference to the object is removed.
-\end{methoddesc}
-
-\begin{methoddesc}[CD parser]{parseframe}{frame}
-Parses one or more frames of digital audio data from a CD such as
-returned by \method{readda()}. It determines which subcodes are
-present in the data. If these subcodes have changed since the last
-frame, then \method{parseframe()} executes a callback of the
-appropriate type passing to it the subcode data found in the frame.
-Unlike the \C{} function, more than one frame of digital audio data
-can be passed to this method.
-\end{methoddesc}
-
-\begin{methoddesc}[CD parser]{removecallback}{type}
-Removes the callback for the given \var{type}.
-\end{methoddesc}
-
-\begin{methoddesc}[CD parser]{resetparser}{}
-Resets the fields of the parser used for tracking subcodes to an
-initial state. \method{resetparser()} should be called after the disc
-has been changed.
-\end{methoddesc}
diff --git a/Doc/lib/libcfgparser.tex b/Doc/lib/libcfgparser.tex
deleted file mode 100644
index 1f33df42e8..0000000000
--- a/Doc/lib/libcfgparser.tex
+++ /dev/null
@@ -1,286 +0,0 @@
-\section{\module{ConfigParser} ---
- Configuration file parser}
-
-\declaremodule{standard}{ConfigParser}
-\modulesynopsis{Configuration file parser.}
-\moduleauthor{Ken Manheimer}{klm@digicool.com}
-\moduleauthor{Barry Warsaw}{bwarsaw@python.org}
-\moduleauthor{Eric S. Raymond}{esr@thyrsus.com}
-\sectionauthor{Christopher G. Petrilli}{petrilli@amber.org}
-
-This module defines the class \class{ConfigParser}.
-\indexii{.ini}{file}\indexii{configuration}{file}\index{ini file}
-\index{Windows ini file}
-The \class{ConfigParser} class implements a basic configuration file
-parser language which provides a structure similar to what you would
-find on Microsoft Windows INI files. You can use this to write Python
-programs which can be customized by end users easily.
-
-\begin{notice}[warning]
- This library does \emph{not} interpret or write the value-type
- prefixes used in the Windows Registry extended version of INI syntax.
-\end{notice}
-
-The configuration file consists of sections, led by a
-\samp{[section]} header and followed by \samp{name: value} entries,
-with continuations in the style of \rfc{822}; \samp{name=value} is
-also accepted. Note that leading whitespace is removed from values.
-The optional values can contain format strings which refer to other
-values in the same section, or values in a special
-\code{DEFAULT} section. Additional defaults can be provided on
-initialization and retrieval. Lines beginning with \character{\#} or
-\character{;} are ignored and may be used to provide comments.
-
-For example:
-
-\begin{verbatim}
-[My Section]
-foodir: %(dir)s/whatever
-dir=frob
-\end{verbatim}
-
-would resolve the \samp{\%(dir)s} to the value of
-\samp{dir} (\samp{frob} in this case). All reference expansions are
-done on demand.
-
-Default values can be specified by passing them into the
-\class{ConfigParser} constructor as a dictionary. Additional defaults
-may be passed into the \method{get()} method which will override all
-others.
-
-\begin{classdesc}{RawConfigParser}{\optional{defaults}}
-The basic configuration object. When \var{defaults} is given, it is
-initialized into the dictionary of intrinsic defaults. This class
-does not support the magical interpolation behavior.
-\versionadded{2.3}
-\end{classdesc}
-
-\begin{classdesc}{ConfigParser}{\optional{defaults}}
-Derived class of \class{RawConfigParser} that implements the magical
-interpolation feature and adds optional arguments the \method{get()}
-and \method{items()} methods. The values in \var{defaults} must be
-appropriate for the \samp{\%()s} string interpolation. Note that
-\var{__name__} is an intrinsic default; its value is the section name,
-and will override any value provided in \var{defaults}.
-\end{classdesc}
-
-\begin{classdesc}{SafeConfigParser}{\optional{defaults}}
-Derived class of \class{ConfigParser} that implements a more-sane
-variant of the magical interpolation feature. This implementation is
-more predictable as well.
-% XXX Need to explain what's safer/more predictable about it.
-New applications should prefer this version if they don't need to be
-compatible with older versions of Python.
-\versionadded{2.3}
-\end{classdesc}
-
-\begin{excdesc}{NoSectionError}
-Exception raised when a specified section is not found.
-\end{excdesc}
-
-\begin{excdesc}{DuplicateSectionError}
-Exception raised when multiple sections with the same name are found,
-or if \method{add_section()} is called with the name of a section that
-is already present.
-\end{excdesc}
-
-\begin{excdesc}{NoOptionError}
-Exception raised when a specified option is not found in the specified
-section.
-\end{excdesc}
-
-\begin{excdesc}{InterpolationError}
-Base class for exceptions raised when problems occur performing string
-interpolation.
-\end{excdesc}
-
-\begin{excdesc}{InterpolationDepthError}
-Exception raised when string interpolation cannot be completed because
-the number of iterations exceeds \constant{MAX_INTERPOLATION_DEPTH}.
-Subclass of \exception{InterpolationError}.
-\end{excdesc}
-
-\begin{excdesc}{InterpolationMissingOptionError}
-Exception raised when an option referenced from a value does not exist.
-Subclass of \exception{InterpolationError}.
-\versionadded{2.3}
-\end{excdesc}
-
-\begin{excdesc}{InterpolationSyntaxError}
-Exception raised when the source text into which substitutions are
-made does not conform to the required syntax.
-Subclass of \exception{InterpolationError}.
-\versionadded{2.3}
-\end{excdesc}
-
-\begin{excdesc}{MissingSectionHeaderError}
-Exception raised when attempting to parse a file which has no section
-headers.
-\end{excdesc}
-
-\begin{excdesc}{ParsingError}
-Exception raised when errors occur attempting to parse a file.
-\end{excdesc}
-
-\begin{datadesc}{MAX_INTERPOLATION_DEPTH}
-The maximum depth for recursive interpolation for \method{get()} when
-the \var{raw} parameter is false. This is relevant only for the
-\class{ConfigParser} class.
-\end{datadesc}
-
-
-\begin{seealso}
- \seemodule{shlex}{Support for a creating \UNIX{} shell-like
- mini-languages which can be used as an alternate
- format for application configuration files.}
-\end{seealso}
-
-
-\subsection{RawConfigParser Objects \label{RawConfigParser-objects}}
-
-\class{RawConfigParser} instances have the following methods:
-
-\begin{methoddesc}{defaults}{}
-Return a dictionary containing the instance-wide defaults.
-\end{methoddesc}
-
-\begin{methoddesc}{sections}{}
-Return a list of the sections available; \code{DEFAULT} is not
-included in the list.
-\end{methoddesc}
-
-\begin{methoddesc}{add_section}{section}
-Add a section named \var{section} to the instance. If a section by
-the given name already exists, \exception{DuplicateSectionError} is
-raised.
-\end{methoddesc}
-
-\begin{methoddesc}{has_section}{section}
-Indicates whether the named section is present in the
-configuration. The \code{DEFAULT} section is not acknowledged.
-\end{methoddesc}
-
-\begin{methoddesc}{options}{section}
-Returns a list of options available in the specified \var{section}.
-\end{methoddesc}
-
-\begin{methoddesc}{has_option}{section, option}
-If the given section exists, and contains the given option. return 1;
-otherwise return 0.
-\versionadded{1.6}
-\end{methoddesc}
-
-\begin{methoddesc}{read}{filenames}
-Read and parse a list of filenames. If \var{filenames} is a string or
-Unicode string, it is treated as a single filename.
-If a file named in \var{filenames} cannot be opened, that file will be
-ignored. This is designed so that you can specify a list of potential
-configuration file locations (for example, the current directory, the
-user's home directory, and some system-wide directory), and all
-existing configuration files in the list will be read. If none of the
-named files exist, the \class{ConfigParser} instance will contain an
-empty dataset. An application which requires initial values to be
-loaded from a file should load the required file or files using
-\method{readfp()} before calling \method{read()} for any optional
-files:
-
-\begin{verbatim}
-import ConfigParser, os
-
-config = ConfigParser.ConfigParser()
-config.readfp(open('defaults.cfg'))
-config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
-\end{verbatim}
-\end{methoddesc}
-
-\begin{methoddesc}{readfp}{fp\optional{, filename}}
-Read and parse configuration data from the file or file-like object in
-\var{fp} (only the \method{readline()} method is used). If
-\var{filename} is omitted and \var{fp} has a \member{name} attribute,
-that is used for \var{filename}; the default is \samp{??>}.
-\end{methoddesc}
-
-\begin{methoddesc}{get}{section, option}
-Get an \var{option} value for the named \var{section}.
-\end{methoddesc}
-
-\begin{methoddesc}{getint}{section, option}
-A convenience method which coerces the \var{option} in the specified
-\var{section} to an integer.
-\end{methoddesc}
-
-\begin{methoddesc}{getfloat}{section, option}
-A convenience method which coerces the \var{option} in the specified
-\var{section} to a floating point number.
-\end{methoddesc}
-
-\begin{methoddesc}{getboolean}{section, option}
-A convenience method which coerces the \var{option} in the specified
-\var{section} to a Boolean value. Note that the accepted values
-for the option are \code{1}, \code{yes}, \code{true}, and \code{on},
-which cause this method to return true, and \code{0}, \code{no},
-\code{false}, and \code{off}, which cause it to return false. These
-values are checked in a case-insensitive manner. Any other value will
-cause it to raise \exception{ValueError}.
-\end{methoddesc}
-
-\begin{methoddesc}{items}{section}
-Return a list of \code{(\var{name}, \var{value})} pairs for each
-option in the given \var{section}.
-\end{methoddesc}
-
-\begin{methoddesc}{set}{section, option, value}
-If the given section exists, set the given option to the specified value;
-otherwise raise \exception{NoSectionError}.
-\versionadded{1.6}
-\end{methoddesc}
-
-\begin{methoddesc}{write}{fileobject}
-Write a representation of the configuration to the specified file
-object. This representation can be parsed by a future \method{read()}
-call.
-\versionadded{1.6}
-\end{methoddesc}
-
-\begin{methoddesc}{remove_option}{section, option}
-Remove the specified \var{option} from the specified \var{section}.
-If the section does not exist, raise \exception{NoSectionError}.
-If the option existed to be removed, return 1; otherwise return 0.
-\versionadded{1.6}
-\end{methoddesc}
-
-\begin{methoddesc}{remove_section}{section}
-Remove the specified \var{section} from the configuration.
-If the section in fact existed, return \code{True}.
-Otherwise return \code{False}.
-\end{methoddesc}
-
-\begin{methoddesc}{optionxform}{option}
-Transforms the option name \var{option} as found in an input file or
-as passed in by client code to the form that should be used in the
-internal structures. The default implementation returns a lower-case
-version of \var{option}; subclasses may override this or client code
-can set an attribute of this name on instances to affect this
-behavior. Setting this to \function{str()}, for example, would make
-option names case sensitive.
-\end{methoddesc}
-
-
-\subsection{ConfigParser Objects \label{ConfigParser-objects}}
-
-The \class{ConfigParser} class extends some methods of the
-\class{RawConfigParser} interface, adding some optional arguments.
-
-\begin{methoddesc}{get}{section, option\optional{, raw\optional{, vars}}}
-Get an \var{option} value for the named \var{section}. All the
-\character{\%} interpolations are expanded in the return values, based
-on the defaults passed into the constructor, as well as the options
-\var{vars} provided, unless the \var{raw} argument is true.
-\end{methoddesc}
-
-\begin{methoddesc}{items}{section\optional{, raw\optional{, vars}}}
-Create a generator which will return a tuple \code{(name, value)} for
-each option in the given \var{section}. Optional arguments have the
-same meaning as for the \code{get()} method.
-\versionadded{2.3}
-\end{methoddesc}
diff --git a/Doc/lib/libcgi.tex b/Doc/lib/libcgi.tex
deleted file mode 100644
index 67e93b4d63..0000000000
--- a/Doc/lib/libcgi.tex
+++ /dev/null
@@ -1,606 +0,0 @@
-\section{\module{cgi} ---
- Common Gateway Interface support.}
-\declaremodule{standard}{cgi}
-
-\modulesynopsis{Common Gateway Interface support, used to interpret
-forms in server-side scripts.}
-
-\indexii{WWW}{server}
-\indexii{CGI}{protocol}
-\indexii{HTTP}{protocol}
-\indexii{MIME}{headers}
-\index{URL}
-
-
-Support module for Common Gateway Interface (CGI) scripts.%
-\index{Common Gateway Interface}
-
-This module defines a number of utilities for use by CGI scripts
-written in Python.
-
-\subsection{Introduction}
-\nodename{cgi-intro}
-
-A CGI script is invoked by an HTTP server, usually to process user
-input submitted through an HTML \code{