From 4117e5428bf1ff3d26d23bd77472265412473ad9 Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Mon, 14 Sep 1998 16:44:15 +0000 Subject: nannified --- Demo/cwilib/cwilib.py | 242 ++++++------- Demo/dns/asgethost.py | 22 +- Demo/metaclasses/Eiffel.py | 70 ++-- Demo/metaclasses/Enum.py | 144 ++++---- Demo/metaclasses/Meta.py | 114 +++--- Demo/metaclasses/Synch.py | 274 +++++++-------- Demo/metaclasses/Trace.py | 134 +++---- Demo/parser/example.py | 146 ++++---- Demo/parser/source.py | 18 +- Demo/parser/test_parser.py | 36 +- Demo/pdist/RCSProxy.py | 178 +++++----- Demo/pdist/makechangelog.py | 110 +++--- Demo/pdist/rcsclient.py | 4 +- Demo/pdist/rcslib.py | 458 ++++++++++++------------ Demo/pysvr/pysvr.py | 130 +++---- Demo/rpc/nfsclient.py | 32 +- Demo/scripts/ftpstats.py | 73 ++-- Demo/scripts/newslist.py | 94 ++--- Demo/sgi/gl/glstdwin/glstdwin.py | 202 +++++------ Demo/sgi/gl/kunst.py | 730 +++++++++++++++++++-------------------- Demo/threads/sync.py | 20 +- Demo/zlib/minigzip.py | 70 ++-- 22 files changed, 1651 insertions(+), 1650 deletions(-) diff --git a/Demo/cwilib/cwilib.py b/Demo/cwilib/cwilib.py index ebe468a..2b19637 100755 --- a/Demo/cwilib/cwilib.py +++ b/Demo/cwilib/cwilib.py @@ -18,22 +18,22 @@ def main(): tn = telnetlib.Telnet(host, 0) # try: - vt.send(tn.read_until('login: ', 10)) - tn.write('cwilib\r') - # - vt.send(tn.read_until('Hit to continue...', 10)) - tn.write('\r') - # - vt.send(tn.read_until('QUIT', 20)) + vt.send(tn.read_until('login: ', 10)) + tn.write('cwilib\r') + # + vt.send(tn.read_until('Hit to continue...', 10)) + tn.write('\r') + # + vt.send(tn.read_until('QUIT', 20)) except EOFError: - sys.stderr.write('Connection closed prematurely\n') - sys.exit(1) + sys.stderr.write('Connection closed prematurely\n') + sys.exit(1) # define_screens(vt) matches = vt.which_screens() if 'menu' not in matches: - sys.stderr.write('Main menu does not appear\n') - sys.exit(1) + sys.stderr.write('Main menu does not appear\n') + sys.exit(1) # tn.write('\r\r') vt.open('Progress -- CWI Library') @@ -41,109 +41,109 @@ def main(): ui = UserInterface() # while 1: - try: - data = tn.read_very_eager() - except EOFError: - stdwin.message('Connection closed--goodbye') - break - if data: - print 'send...' - vt.send(data) - print 'send...done' - continue - event = stdwin.pollevent() - if event: - type, window, detail = event - if window == None and type == WE_LOST_SEL: - window = ui.queryform.window - event = type, window, detail - if type == WE_CLOSE: - break - if window in ui.windows: - ui.dispatch(type, window, detail) - elif window == vt.window: - if type == WE_NULL: - pass - elif type == WE_COMMAND: - if detail == WC_RETURN: - tn.write('\r') - elif detail == WC_BACKSPACE: - tn.write('\b') - elif detail == WC_TAB: - tn.write('\t') - elif detail == WC_UP: - tn.write('\033[A') - elif detail == WC_DOWN: - tn.write('\033[B') - elif detail == WC_RIGHT: - tn.write('\033[C') - elif detail == WC_LEFT: - tn.write('\033[D') - else: - print '*** Command:', detail - elif type == WE_CHAR: - tn.write(detail) - elif type == WE_DRAW: - vt.draw(detail) - elif type in (WE_ACTIVATE, WE_DEACTIVATE): - pass - else: - print '*** VT100 event:', type, detail - else: - print '*** Alien event:', type, window, detail - continue - rfd, wfd, xfd = select.select([tn, stdwin], [], []) + try: + data = tn.read_very_eager() + except EOFError: + stdwin.message('Connection closed--goodbye') + break + if data: + print 'send...' + vt.send(data) + print 'send...done' + continue + event = stdwin.pollevent() + if event: + type, window, detail = event + if window == None and type == WE_LOST_SEL: + window = ui.queryform.window + event = type, window, detail + if type == WE_CLOSE: + break + if window in ui.windows: + ui.dispatch(type, window, detail) + elif window == vt.window: + if type == WE_NULL: + pass + elif type == WE_COMMAND: + if detail == WC_RETURN: + tn.write('\r') + elif detail == WC_BACKSPACE: + tn.write('\b') + elif detail == WC_TAB: + tn.write('\t') + elif detail == WC_UP: + tn.write('\033[A') + elif detail == WC_DOWN: + tn.write('\033[B') + elif detail == WC_RIGHT: + tn.write('\033[C') + elif detail == WC_LEFT: + tn.write('\033[D') + else: + print '*** Command:', detail + elif type == WE_CHAR: + tn.write(detail) + elif type == WE_DRAW: + vt.draw(detail) + elif type in (WE_ACTIVATE, WE_DEACTIVATE): + pass + else: + print '*** VT100 event:', type, detail + else: + print '*** Alien event:', type, window, detail + continue + rfd, wfd, xfd = select.select([tn, stdwin], [], []) # Subroutine to define our screen recognition patterns def define_screens(vt): vt.define_screen('menu', { - 'title': ('search', 0, 0, 80, - ' SEARCH FUNCTIONS +OTHER FUNCTIONS '), - }) + 'title': ('search', 0, 0, 80, + ' SEARCH FUNCTIONS +OTHER FUNCTIONS '), + }) vt.define_screen('search', { - 'title': ('search', 0, 0, 80, ' Search '), - }) + 'title': ('search', 0, 0, 80, ' Search '), + }) vt.define_screen('shortlist', {'title': ('search', 0, 0, 80, - ' Short-list')}) + ' Short-list')}) vt.define_screen('showrecord', { - 'title': ('search', 0, 0, 80, ' Show record '), - }) + 'title': ('search', 0, 0, 80, ' Show record '), + }) vt.define_screen('timelimit', { - 'limit': ('search', 12, 0, 80, ' TIME LIMIT '), - }) + 'limit': ('search', 12, 0, 80, ' TIME LIMIT '), + }) vt.define_screen('attention', { - 'BASE': ('copy', 0, 0, 0, 'search'), - 'title': ('search', 10, 0, 80, ' ATTENTION ')}) + 'BASE': ('copy', 0, 0, 0, 'search'), + 'title': ('search', 10, 0, 80, ' ATTENTION ')}) vt.define_screen('syntaxerror', { - 'BASE': ('copy', 0, 0, 0, 'attention'), - 'message': ('search', 12, 0, 80, ' Syntax error'), - }) + 'BASE': ('copy', 0, 0, 0, 'attention'), + 'message': ('search', 12, 0, 80, ' Syntax error'), + }) vt.define_screen('emptyerror', { - 'BASE': ('copy', 0, 0, 0, 'attention'), - 'message': ('search', 12, 0, 80, - ' Check your input. Search at least one term'), - }) + 'BASE': ('copy', 0, 0, 0, 'attention'), + 'message': ('search', 12, 0, 80, + ' Check your input. Search at least one term'), + }) vt.define_screen('unsortedwarning', { - 'BASE': ('copy', 0, 0, 0, 'attention'), - 'message': ('search', 12, 0, 80, - ' Number of records exceeds sort limit'), - }) + 'BASE': ('copy', 0, 0, 0, 'attention'), + 'message': ('search', 12, 0, 80, + ' Number of records exceeds sort limit'), + }) vt.define_screen('thereismore', { - 'BASE': ('copy', 0, 0, 0, 'showrecord'), - 'message': ('search', 15, 0, 80, - 'There is more within this record. Use the arrow keys'), - }) + 'BASE': ('copy', 0, 0, 0, 'showrecord'), + 'message': ('search', 15, 0, 80, + 'There is more within this record. Use the arrow keys'), + }) vt.define_screen('nofurther', { - 'BASE': ('copy', 0, 0, 0, 'showrecord'), - 'message': ('search', 17, 0, 80, 'You cannot go further\.'), - }) + 'BASE': ('copy', 0, 0, 0, 'showrecord'), + 'message': ('search', 17, 0, 80, 'You cannot go further\.'), + }) vt.define_screen('nofurtherback', { - 'BASE': ('copy', 0, 0, 0, 'showrecord'), - 'message': ('search', 17, 0, 80, - 'You cannot go further back'), - }) + 'BASE': ('copy', 0, 0, 0, 'showrecord'), + 'message': ('search', 17, 0, 80, + 'You cannot go further back'), + }) # Class to implement our user interface. @@ -151,29 +151,29 @@ def define_screens(vt): class UserInterface: def __init__(self): - stdwin.setfont('7x14') - self.queryform = QueryForm() - self.listform = ListForm() - self.recordform = RecordForm() - self.forms = [self.queryform, self.listform, self.recordform] - define_query_fields(self.queryform) - self.windows = [] - for form in self.forms: - if form.formheight > 0: - form.open() - self.windows.append(form.window) + stdwin.setfont('7x14') + self.queryform = QueryForm() + self.listform = ListForm() + self.recordform = RecordForm() + self.forms = [self.queryform, self.listform, self.recordform] + define_query_fields(self.queryform) + self.windows = [] + for form in self.forms: + if form.formheight > 0: + form.open() + self.windows.append(form.window) def __del__(self): - self.close() + self.close() def close(self): - for form in self.forms: - form.close() + for form in self.forms: + form.close() def dispatch(self, type, window, detail): - for form in self.forms: - if window == form.window: - form.dispatch(type, detail) + for form in self.forms: + if window == form.window: + form.dispatch(type, detail) def define_query_fields(f): @@ -189,25 +189,25 @@ def define_query_fields(f): class QueryForm(Form): def __init__(self): - Form.__init__(self, 'Query form -- CWI Library') + Form.__init__(self, 'Query form -- CWI Library') def dispatch(self, type, detail): - if type == WE_COMMAND and detail == WC_RETURN: - print '*** SUBMIT ***' - else: - Form.dispatch(self, type, detail) + if type == WE_COMMAND and detail == WC_RETURN: + print '*** SUBMIT ***' + else: + Form.dispatch(self, type, detail) class ListForm(Form): def __init__(self): - Form.__init__(self, 'Short list -- CWI Library') + Form.__init__(self, 'Short list -- CWI Library') class RecordForm(Form): def __init__(self): - Form.__init__(self, 'Record detail -- CWI Library') + Form.__init__(self, 'Record detail -- CWI Library') main() diff --git a/Demo/dns/asgethost.py b/Demo/dns/asgethost.py index 9a90268..2e9185a 100755 --- a/Demo/dns/asgethost.py +++ b/Demo/dns/asgethost.py @@ -7,7 +7,7 @@ import socket import select def main(): - server = 'cnri.reston.va.us' # How? + server = 'cnri.reston.va.us' # How? port = 53 opcode = dnsopcode.QUERY rd = 0 @@ -15,21 +15,21 @@ def main(): qname = sys.argv[1:] and sys.argv[1] or 'www.python.org' m = dnslib.Mpacker() m.addHeader(0, - 0, opcode, 0, 0, rd, 0, 0, 0, - 1, 0, 0, 0) + 0, opcode, 0, 0, rd, 0, 0, 0, + 1, 0, 0, 0) m.addQuestion(qname, qtype, dnsclass.IN) request = m.getbuf() s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((server, port)) s.send(request) while 1: - r, w, x = [s], [], [] - r, w, x = select.select(r, w, x, 0.333) - print r, w, x - if r: - reply = s.recv(1024) - u = dnslib.Munpacker(reply) - dnslib.dumpM(u) - break + r, w, x = [s], [], [] + r, w, x = select.select(r, w, x, 0.333) + print r, w, x + if r: + reply = s.recv(1024) + u = dnslib.Munpacker(reply) + dnslib.dumpM(u) + break main() diff --git a/Demo/metaclasses/Eiffel.py b/Demo/metaclasses/Eiffel.py index 38ee6bc..d9c8a9a 100644 --- a/Demo/metaclasses/Eiffel.py +++ b/Demo/metaclasses/Eiffel.py @@ -4,19 +4,19 @@ For example, class C: def m1(self, arg): - require arg > 0 - return whatever + require arg > 0 + return whatever ensure Result > arg can be written (clumsily, I agree) as: class C(Eiffel): def m1(self, arg): - return whatever + return whatever def m1_pre(self, arg): - assert arg > 0 + assert arg > 0 def m1_post(self, Result, arg): - assert 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 @@ -28,10 +28,10 @@ post-condition with that defined in the derived class', for example: class D(C): def m1(self, arg): - return whatever**2 + return whatever**2 def m1_post(self, Result, arg): - C.m1_post(self, Result, arg) - assert Result < 100 + 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. @@ -42,13 +42,13 @@ 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 + pass but one could equally write a derived class that makes a stronger requirement: def m1_pre(self, arg): - require arg > 50 + 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). @@ -66,27 +66,27 @@ 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 + 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 + 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 @@ -99,12 +99,12 @@ 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 + 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) diff --git a/Demo/metaclasses/Enum.py b/Demo/metaclasses/Enum.py index e1ae695..13a3ed7 100644 --- a/Demo/metaclasses/Enum.py +++ b/Demo/metaclasses/Enum.py @@ -12,9 +12,9 @@ class EnumMetaClass: To define your own enumeration, do something like class Color(Enum): - red = 1 - green = 2 - blue = 3 + red = 1 + green = 2 + blue = 3 Now, Color.red, Color.green and Color.blue behave totally different: they are enumerated values, not integers. @@ -25,66 +25,66 @@ class EnumMetaClass: """ 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) + """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. + """Return an enumeration value. - For example, Color.red returns the value corresponding to red. + For example, Color.red returns the value corresponding to red. - XXX Perhaps the values should be created in the constructor? + 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. + 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). + 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() + """ + 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 + try: + return self.__dict[name] + except KeyError: + for base in self.__bases__: + try: + return getattr(base, name) + except AttributeError: + continue - raise AttributeError, name + 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 + 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: @@ -99,23 +99,23 @@ class EnumInstance: """ def __init__(self, classname, enumname, value): - self.__classname = classname - self.__enumname = enumname - self.__value = value + self.__classname = classname + self.__enumname = enumname + self.__value = value def __int__(self): - return self.__value + return self.__value def __repr__(self): - return "EnumInstance(%s, %s, %s)" % (`self.__classname`, - `self.__enumname`, - `self.__value`) + return "EnumInstance(%s, %s, %s)" % (`self.__classname`, + `self.__enumname`, + `self.__value`) def __str__(self): - return "%s.%s" % (self.__classname, self.__enumname) + return "%s.%s" % (self.__classname, self.__enumname) def __cmp__(self, other): - return cmp(self.__value, int(other)) + return cmp(self.__value, int(other)) # Create the base class for enumerations. @@ -126,9 +126,9 @@ Enum = EnumMetaClass("Enum", (), {}) def _test(): class Color(Enum): - red = 1 - green = 2 - blue = 3 + red = 1 + green = 2 + blue = 3 print Color.red print dir(Color) @@ -139,11 +139,11 @@ def _test(): print Color.red == 2 class ExtendedColor(Color): - white = 0 - orange = 4 - yellow = 5 - purple = 6 - black = 7 + white = 0 + orange = 4 + yellow = 5 + purple = 6 + black = 7 print ExtendedColor.orange print ExtendedColor.red @@ -151,11 +151,11 @@ def _test(): print Color.red == ExtendedColor.red class OtherColor(Enum): - white = 4 - blue = 5 + white = 4 + blue = 5 class MergedColor(Color, OtherColor): - pass + pass print MergedColor.red print MergedColor.white diff --git a/Demo/metaclasses/Meta.py b/Demo/metaclasses/Meta.py index 76193c1..771205c 100644 --- a/Demo/metaclasses/Meta.py +++ b/Demo/metaclasses/Meta.py @@ -9,33 +9,33 @@ import types class MetaMethodWrapper: def __init__(self, func, inst): - self.func = func - self.inst = inst - self.__name__ = self.func.__name__ + self.func = func + self.inst = inst + self.__name__ = self.func.__name__ def __call__(self, *args, **kw): - return apply(self.func, (self.inst,) + 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 + 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: - raise AttributeError, name - return ga(self, name) - if type(raw) != types.FunctionType: - return raw - return self.__methodwrapper__(raw, self) + # 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: + raise AttributeError, name + return ga(self, name) + if type(raw) != types.FunctionType: + return raw + return self.__methodwrapper__(raw, self) class MetaClass: @@ -45,49 +45,49 @@ class MetaClass: """ - __helper__ = MetaHelper # For derived metaclasses to override + __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 + 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 + 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 + 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 + 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', (), {}) @@ -95,18 +95,18 @@ 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` + 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 + def __getattr__(self, name): + if name[:2] == '__': raise AttributeError, name + return "getattr:%s" % name x = D() print x.foo print x._foo diff --git a/Demo/metaclasses/Synch.py b/Demo/metaclasses/Synch.py index 1fb9160..df70337 100644 --- a/Demo/metaclasses/Synch.py +++ b/Demo/metaclasses/Synch.py @@ -40,64 +40,64 @@ class Lock: """ def __init__(self): - """Constructor. Initialize all instance variables.""" - self.__mutex = thread.allocate_lock() - self.__wait = thread.allocate_lock() - self.__tid = None - self.__count = 0 + """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() + """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. + """Release the lock. - If this thread doesn't currently have the lock, an assertion - error is raised. + 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. + 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() + """ + 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(): @@ -105,23 +105,23 @@ 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) + 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.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 + f1(lock) # Adds 2 to done lock.release() lock.acquire() @@ -134,8 +134,8 @@ def _testLock(): lock.release() import time while len(done) < 9: - print len(done) - time.sleep(0.001) + print len(done) + time.sleep(0.001) print len(done) @@ -147,19 +147,19 @@ 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() + 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() + MetaHelper.__helperinit__(self, formalclass) + self.__lock__ = Lock() class LockingMetaClass(MetaClass): __helper__ = LockingHelper @@ -169,73 +169,73 @@ 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 __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() + 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() + 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() diff --git a/Demo/metaclasses/Trace.py b/Demo/metaclasses/Trace.py index a5b765a..86e199d 100644 --- a/Demo/metaclasses/Trace.py +++ b/Demo/metaclasses/Trace.py @@ -20,38 +20,38 @@ class TraceMetaClass: __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 + 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 + 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 + 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 + 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 @@ -59,52 +59,52 @@ class TracingInstance: """Helper class to represent an instance of a tracing class.""" def __trace_call__(self, fp, fmt, *args): - fp.write((fmt+'\n') % args) + fp.write((fmt+'\n') % args) def __meta_init__(self, klass): - self.__class = 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) + # 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 + self.__name__ = name + self.func = func + self.inst = inst def __call__(self, *args, **kw): - return apply(self.func, (self.inst,) + 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 + 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}) @@ -112,13 +112,13 @@ 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 + 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 + 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 diff --git a/Demo/parser/example.py b/Demo/parser/example.py index 363f5bb..821cef0 100644 --- a/Demo/parser/example.py +++ b/Demo/parser/example.py @@ -14,7 +14,7 @@ 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. + Name of the file to read Python source code from. """ source = open(fileName).read() import os @@ -30,86 +30,86 @@ class SuiteInfoBase: _name = '' def __init__(self, tree = None): - self._class_info = {} - self._function_info = {} - if tree: - self._extract_info(tree) + 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) + # 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 + return self._docstring def get_name(self): - return self._name + return self._name def get_class_names(self): - return self._class_info.keys() + return self._class_info.keys() def get_class_info(self, name): - return self._class_info[name] + return self._class_info[name] def __getitem__(self, name): - try: - return self._class_info[name] - except KeyError: - return self._function_info[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() + return self._function_info.keys() def get_function_info(self, name): - return self._function_info[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) + 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) + self._name = tree[2][1] + SuiteInfoBase.__init__(self, tree and tree[-1] or None) def get_method_names(self): - return self._function_info.keys() + return self._function_info.keys() def get_method_info(self, name): - return self._function_info[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"] + self._name = name + SuiteInfoBase.__init__(self, tree) + if tree: + found, vars = match(DOCSTRING_STMT_PATTERN, tree[1]) + if found: + self._docstring = vars["docstring"] from types import ListType, TupleType @@ -118,14 +118,14 @@ def match(pattern, data, vars=None): """Match `data' to `pattern', with variable extraction. pattern - Pattern to match against, possibly containing variables. + Pattern to match against, possibly containing variables. data - Data to be checked and against which variables are extracted. + 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. + 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 @@ -138,18 +138,18 @@ def match(pattern, data, vars=None): values. """ if vars is None: - vars = {} - if type(pattern) is ListType: # 'variables' are ['varname'] - vars[pattern[0]] = data - return 1, vars + 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 + return (pattern == data), vars if len(data) != len(pattern): - return 0, vars + return 0, vars for pattern, data in map(None, pattern, data): - same, vars = match(pattern, data, vars) - if not same: - break + same, vars = match(pattern, data, vars) + if not same: + break return same, vars @@ -172,21 +172,21 @@ DOCSTRING_STMT_PATTERN = ( (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']) - )))))))))))))))), + (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/source.py b/Demo/parser/source.py index b1690a5..b900628 100644 --- a/Demo/parser/source.py +++ b/Demo/parser/source.py @@ -9,18 +9,18 @@ class Simple: "This class does very little." def method(self): - "This method does almost nothing." - return 1 + "This method does almost nothing." + return 1 class Nested: - "This is a nested class." + "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 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." diff --git a/Demo/parser/test_parser.py b/Demo/parser/test_parser.py index f91592f..3f02a96 100755 --- a/Demo/parser/test_parser.py +++ b/Demo/parser/test_parser.py @@ -11,24 +11,24 @@ 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) + 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 + 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.' + 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() @@ -38,8 +38,8 @@ def test(): import sys args = sys.argv[1:] if not args: - import glob - args = glob.glob("*.py") + import glob + args = glob.glob("*.py") map(testFile, args) sys.exit(_numFailed != 0) diff --git a/Demo/pdist/RCSProxy.py b/Demo/pdist/RCSProxy.py index e29090c..7212ca6 100755 --- a/Demo/pdist/RCSProxy.py +++ b/Demo/pdist/RCSProxy.py @@ -31,147 +31,147 @@ import rcslib class DirSupport: def __init__(self): - self._dirstack = [] + self._dirstack = [] def __del__(self): - self._close() + self._close() def _close(self): - while self._dirstack: - self.back() + while self._dirstack: + self.back() def pwd(self): - return os.getcwd() + return os.getcwd() def cd(self, name): - save = os.getcwd() - os.chdir(name) - self._dirstack.append(save) + 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] + 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) + 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) + return os.path.isdir(name) def mkdir(self, name): - os.mkdir(name, 0777) + os.mkdir(name, 0777) def rmdir(self, name): - os.rmdir(name) + os.rmdir(name) class RCSProxyLocal(rcslib.RCS, DirSupport): def __init__(self): - rcslib.RCS.__init__(self) - DirSupport.__init__(self) + rcslib.RCS.__init__(self) + DirSupport.__init__(self) def __del__(self): - DirSupport.__del__(self) - rcslib.RCS.__del__(self) + DirSupport.__del__(self) + rcslib.RCS.__del__(self) def sumlist(self, list = None): - return self._list(self.sum, list) + return self._list(self.sum, list) def sumdict(self, list = None): - return self._dict(self.sum, list) + 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() + 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 + 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) + 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. + """INTERNAL: apply FUNCTION to all files in LIST. - Return a list of the results. + Return a list of the results. - The list defaults to all files in the directory if None. + 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 + """ + 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. + """INTERNAL: apply FUNCTION to all files in LIST. - Return a dictionary mapping files to results. + Return a dictionary mapping files to results. - The list defaults to all files in the directory if None. + 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 + """ + 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) + RCSProxyLocal.__init__(self) + server.SecureServer.__init__(self, address, verbose) def _close(self): - server.SecureServer._close(self) - RCSProxyLocal._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() + 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]) + port = string.atoi(sys.argv[1]) else: - port = 4127 + port = 4127 proxy = RCSProxyServer(('', port)) proxy._serverloop() @@ -179,19 +179,19 @@ def test_server(): 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) + 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` + 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) + print "%s: no such attribute" % what + sys.exit(2) if __name__ == '__main__': diff --git a/Demo/pdist/makechangelog.py b/Demo/pdist/makechangelog.py index 5a0cf79..b26f30b 100755 --- a/Demo/pdist/makechangelog.py +++ b/Demo/pdist/makechangelog.py @@ -15,25 +15,25 @@ def main(): opts, args = getopt.getopt(args, 'p:') prefix = '' for o, a in opts: - if p == '-p': prefix = a + 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 + 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) + formatrev(rev, prefix) parsedateprog = regex.compile( '^date: \([0-9]+\)/\([0-9]+\)/\([0-9]+\) ' + @@ -48,46 +48,46 @@ authormap = { 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 + 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, + 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 @@ -95,14 +95,14 @@ def getnextrev(f, file): 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 + 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__': diff --git a/Demo/pdist/rcsclient.py b/Demo/pdist/rcsclient.py index 20dffec..5d88a57 100755 --- a/Demo/pdist/rcsclient.py +++ b/Demo/pdist/rcsclient.py @@ -22,8 +22,8 @@ import client class RCSProxyClient(client.SecureClient): - def __init__(self, address, verbose = client.VERBOSE): - client.SecureClient.__init__(self, address, verbose) + def __init__(self, address, verbose = client.VERBOSE): + client.SecureClient.__init__(self, address, verbose) def openrcsclient(opts = []): diff --git a/Demo/pdist/rcslib.py b/Demo/pdist/rcslib.py index 55d764d..223ddca 100755 --- a/Demo/pdist/rcslib.py +++ b/Demo/pdist/rcslib.py @@ -36,304 +36,304 @@ class RCS: okchars = string.letters + string.digits + '-_=+.' def __init__(self): - """Constructor.""" - pass + """Constructor.""" + pass def __del__(self): - """Destructor.""" - pass + """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. + """Return the full log text for NAME_REV as a string. - Optional OTHERFLAGS are passed to rlog. + 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 + """ + 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'] + """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 + """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) + """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) + """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. + """Check out NAME_REV to its work file. - If optional WITHLOCK is set, check out locked, else unlocked. + If optional WITHLOCK is set, check out locked, else unlocked. - The optional OTHERFLAGS is passed to co without - interpretation. + The optional OTHERFLAGS is passed to co without + interpretation. - Any output from co goes to directly to stdout. + 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) + """ + 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" - textfile = None - try: - if new: - textfile = tempfile.mktemp() - f = open(textfile, 'w') - f.write(message) - f.close() - cmd = 'ci %s%s -t%s %s %s' % \ - (lockflag, rev, textfile, 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) - finally: - if textfile: self._remove(textfile) + """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" + textfile = None + try: + if new: + textfile = tempfile.mktemp() + f = open(textfile, 'w') + f.write(message) + f.close() + cmd = 'ci %s%s -t%s %s %s' % \ + (lockflag, rev, textfile, 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) + finally: + if textfile: self._remove(textfile) # --- 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) + """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))) + """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 + """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. + """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. + 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 + """ + 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) + """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. + """Normalize NAME_REV into a (NAME, REV) tuple. - Raise an exception if there is no corresponding version file. + 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 + """ + 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. + """INTERNAL: open a read pipe to NAME_REV using optional COMMAND. - Optional FLAG is used to indicate the revision (default -r). + Optional FLAG is used to indicate the revision (default -r). - Default COMMAND is "co -p". + Default COMMAND is "co -p". - Return a file object connected by a pipe to the command's - output. + 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`)) + """ + 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. + """INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple. - Raise an exception if NAME contains invalid characters. + 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). + 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 + """ + 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 + """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. + """INTERNAL: run COMMAND in a subshell. - Standard input for the command is taken fron /dev/null. + Standard input for the command is taken fron /dev/null. - Raise IOError when the exit status is not zero. + Raise IOError when the exit status is not zero. - Return whatever the calling method should return; normally - None. + 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. + A derived class may override this method and redefine it to + capture stdout/stderr of the command and return it. - """ - cmd = cmd + " 1: - raise getopt.error, "Too many arguments." + opts, args = getopt.getopt(sys.argv[1:], "") + if len(args) > 1: + raise getopt.error, "Too many arguments." except getopt.error, msg: - usage(msg) + usage(msg) for o, a in opts: - pass + pass if args: - try: - port = string.atoi(args[0]) - except ValueError, msg: - usage(msg) + try: + port = string.atoi(args[0]) + except ValueError, msg: + usage(msg) else: - port = PORT + port = PORT main_thread(port) def usage(msg=None): sys.stdout = sys.stderr if msg: - print msg + print msg print "\n", __doc__, sys.exit(2) @@ -47,18 +47,18 @@ def main_thread(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 + (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), + caddr), stdin = conn.makefile("r") stdout = conn.makefile("w", 0) run_interpreter(stdin, stdout) @@ -67,57 +67,57 @@ def service_thread(conn, addr): def run_interpreter(stdin, stdout): globals = {} try: - str(sys.ps1) + str(sys.ps1) except: - sys.ps1 = ">>> " + 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(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 + 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 diff --git a/Demo/rpc/nfsclient.py b/Demo/rpc/nfsclient.py index 498e2d0..1bd5d0d 100644 --- a/Demo/rpc/nfsclient.py +++ b/Demo/rpc/nfsclient.py @@ -96,22 +96,22 @@ class NFSUnpacker(MountUnpacker): 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) + 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() diff --git a/Demo/scripts/ftpstats.py b/Demo/scripts/ftpstats.py index e931751..28b1d8b 100755 --- a/Demo/scripts/ftpstats.py +++ b/Demo/scripts/ftpstats.py @@ -53,44 +53,45 @@ def main(): 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) + 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) + 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) diff --git a/Demo/scripts/newslist.py b/Demo/scripts/newslist.py index 59ffde4..f78ca30 100755 --- a/Demo/scripts/newslist.py +++ b/Demo/scripts/newslist.py @@ -96,11 +96,11 @@ sublistsize = 4 ####################################################################### 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 + rcfile = os.path.join(dir, '.newslistrc.py') + if os.path.exists(rcfile): + print rcfile + execfile(rcfile) + break from nntplib import NNTP from stat import * @@ -120,8 +120,8 @@ page = os.path.join(topdir,pagedir) def addtotree(tree, groups): print 'Updating tree...' for i in groups: - parts = string.splitfields(i,'.') - makeleaf(tree, parts) + parts = string.splitfields(i,'.') + makeleaf(tree, parts) # Makeleaf makes a leaf and the branch leading to it if necessary def makeleaf(tree,path): @@ -135,7 +135,7 @@ def makeleaf(tree,path): if l > 1: makeleaf(tree[j],path[1:]) -# Then the bits for outputting trees as pages ---------------- +# Then the bits for outputting trees as pages ---------------- # Createpage creates an HTML file named .html containing links # to those groups beginning with . @@ -177,24 +177,24 @@ def printtree(f, tree, indent, p): if l > 1: kl.sort() if indent > 0: - # Create a sub-list - f.write('
  • '+p[1:]+'\n