diff options
Diffstat (limited to 'Demo')
-rw-r--r-- | Demo/README | 3 | ||||
-rwxr-xr-x | Demo/classes/Dates.py | 70 | ||||
-rw-r--r-- | Demo/curses/README | 5 | ||||
-rwxr-xr-x | Demo/curses/life.py | 128 | ||||
-rw-r--r-- | Demo/curses/rain.py | 4 | ||||
-rwxr-xr-x | Demo/curses/repeat.py | 4 | ||||
-rw-r--r-- | Demo/curses/tclock.py | 25 | ||||
-rw-r--r-- | Demo/curses/xmas.py | 6 | ||||
-rw-r--r-- | Demo/sockets/README | 1 | ||||
-rw-r--r-- | Demo/sockets/unixclient.py | 4 | ||||
-rw-r--r-- | Demo/sockets/unixserver.py | 15 | ||||
-rw-r--r-- | Demo/threads/fcmp.py | 6 | ||||
-rw-r--r-- | Demo/xmlrpc/xmlrpc_handler.py | 104 | ||||
-rw-r--r-- | Demo/xmlrpc/xmlrpcserver.py | 75 | ||||
-rwxr-xr-x | Demo/zlib/minigzip.py | 147 | ||||
-rwxr-xr-x | Demo/zlib/zlibdemo.py | 77 |
16 files changed, 266 insertions, 408 deletions
diff --git a/Demo/README b/Demo/README index 5e3d9e2..9d150d6 100644 --- a/Demo/README +++ b/Demo/README @@ -57,8 +57,5 @@ tkinter Demos using the Tk interface (including Matt Conway's xml Some XML demos. -xmlrpc XML-RPC server framework (but see the standard library - module SimpleXMLRPCServer.py for a replacement). - zlib Some demos for the zlib module (see also the standard library module gzip.py). diff --git a/Demo/classes/Dates.py b/Demo/classes/Dates.py index f8f0634..6494b6a 100755 --- a/Demo/classes/Dates.py +++ b/Demo/classes/Dates.py @@ -59,32 +59,32 @@ del dbm, dim _INT_TYPES = type(1), type(1L) -def _is_leap( year ): # 1 if leap year, else 0 +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 +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 +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 +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 +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 ) + \ +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 +_DI400Y = _days_before_year(400) # number of days in 400 years -def _num2date( n ): # return date with ordinal n +def _num2date(n): # return date with ordinal n if type(n) not in _INT_TYPES: raise TypeError, 'argument must be integer: %r' % type(n) @@ -95,53 +95,53 @@ def _num2date( n ): # return date with ordinal 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 ) + dby = _days_before_year(more) if dby >= n: more = more - 1 - dby = dby - _days_in_year( more ) + 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 ) + 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 ) + 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 +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 ): + def __init__(self, month, day, year): if not 1 <= month <= 12: raise ValueError, 'month must be in 1..12: %r' % (month,) - dim = _days_in_month( month, year ) + dim = _days_in_month(month, year) if not 1 <= day <= dim: raise ValueError, 'day must be in 1..%r: %r' % (dim, day) self.month, self.day, self.year = month, day, year - self.ord = _date2num( self ) + self.ord = _date2num(self) # don't allow setting existing attributes - def __setattr__( self, name, value ): + 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 ) + 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 ) + def __hash__(self): + return hash(self.ord) # print as, e.g., Mon 16 Aug 1993 - def __repr__( self ): + def __repr__(self): return '%.3s %2d %.3s %r' % ( self.weekday(), self.day, @@ -149,33 +149,33 @@ class Date: self.year) # Python 1.1 coerces neither int+date nor date+int - def __add__( self, n ): + def __add__(self, n): if type(n) not in _INT_TYPES: raise TypeError, 'can\'t add %r to date' % type(n) - return _num2date( self.ord + n ) + return _num2date(self.ord + n) __radd__ = __add__ # handle int+date # Python 1.1 coerces neither date-int nor date-date - def __sub__( self, other ): + def __sub__(self, other): if type(other) in _INT_TYPES: # date-int - return _num2date( self.ord - other ) + return _num2date(self.ord - other) else: return self.ord - other.ord # date-date # complain about int-date - def __rsub__( self, other ): + def __rsub__(self, other): raise TypeError, 'Can\'t subtract date from integer' - def weekday( self ): - return _num2day( self.ord ) + def weekday(self): + return _num2day(self.ord) def today(): import time local = time.localtime(time.time()) - return Date( local[1], local[2], local[0] ) + return Date(local[1], local[2], local[0]) DateTestError = 'DateTestError' -def test( firstyear, lastyear ): +def test(firstyear, lastyear): a = Date(9,30,1913) b = Date(9,30,1914) if repr(a) != 'Tue 30 Sep 1913': @@ -207,7 +207,7 @@ def test( firstyear, lastyear ): # verify date<->number conversions for first and last days for # all years in firstyear .. lastyear - lord = _days_before_year( firstyear ) + lord = _days_before_year(firstyear) y = firstyear while y <= lastyear: ford = lord + 1 diff --git a/Demo/curses/README b/Demo/curses/README index f2a3b74..2d1c4b1 100644 --- a/Demo/curses/README +++ b/Demo/curses/README @@ -11,14 +11,11 @@ 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 -(<URL:http://sourceforge.net/bugs/?group_id=5470>). +Please submit bugfixes and new contributions to the Python bug tracker. Other demos diff --git a/Demo/curses/life.py b/Demo/curses/life.py index a787e26..a5bbed2 100755 --- a/Demo/curses/life.py +++ b/Demo/curses/life.py @@ -44,14 +44,15 @@ class LifeBoard: scr -- curses screen object to use for display char -- character used to render live cells (default: '*') """ - self.state={} ; self.scr=scr + 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*'-')+'+' + 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): @@ -73,16 +74,16 @@ class LifeBoard: del self.state[x,y] self.scr.addch(y+1, x+1, ' ') else: - self.state[x,y]=1 + 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) + self.state = {} + self.display(update_board=False) - def display(self, update_board=1): + def display(self, update_board=True): """Display the whole board, optionally computing one generation""" M,N = self.X, self.Y if not update_board: @@ -95,42 +96,46 @@ class LifeBoard: self.scr.refresh() return - d={} ; self.boring=1 + d = {} + self.boring = 1 for i in range(0, M): - L=range( max(0, i-1), min(M, i+2) ) + 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) ) + 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: + s += 1 + s -= live + if s == 3: # Birth - d[i,j]=1 + 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 + 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.boring = 0 + self.state = d self.scr.refresh() def makeRandom(self): "Fill the board with a random pattern" - self.state={} + 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) + 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() + 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" @@ -140,18 +145,17 @@ def display_menu(stdscr, menu_y): stdscr.addstr(menu_y+1, 4, 'E)rase the board, R)andom fill, S)tep once or C)ontinuously, Q)uit') -def main(stdscr): - +def keyloop(stdscr): # Clear the screen and display the menu of keys stdscr.clear() stdscr_y, stdscr_x = stdscr.getmaxyx() - menu_y=(stdscr_y-3)-1 + 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) + subwin = stdscr.subwin(stdscr_y-3, stdscr_x, 0, 0) + board = LifeBoard(subwin, char=ord('*')) + board.display(update_board=False) # xpos, ypos are the cursor's position xpos, ypos = board.X/2, board.Y/2 @@ -159,9 +163,9 @@ def main(stdscr): # Main loop: while (1): stdscr.move(1+ypos, 1+xpos) # Move the cursor - c=stdscr.getch() # Get a keystroke + c = stdscr.getch() # Get a keystroke if 0<c<256: - c=chr(c) + c = chr(c) if c in ' \n': board.toggle(ypos, xpos) elif c in 'Cc': @@ -173,50 +177,40 @@ def main(stdscr): # if no keystroke is available, instead of waiting. stdscr.nodelay(1) while (1): - c=stdscr.getch() - if c!=-1: break - stdscr.addstr(0,0, '/'); stdscr.refresh() + c = stdscr.getch() + if c != -1: + break + stdscr.addstr(0,0, '/') + stdscr.refresh() board.display() - stdscr.addstr(0,0, '+'); stdscr.refresh() + stdscr.addstr(0,0, '+') + stdscr.refresh() stdscr.nodelay(0) # Disable nodelay mode display_menu(stdscr, menu_y) - elif c in 'Ee': board.erase() - elif c in 'Qq': break + elif c in 'Ee': + board.erase() + elif c in 'Qq': + break elif c in 'Rr': board.makeRandom() - board.display(update_board=0) + board.display(update_board=False) elif c in 'Ss': board.display() else: pass # Ignore incorrect keys - elif c==curses.KEY_UP and ypos>0: ypos=ypos-1 - elif c==curses.KEY_DOWN and ypos<board.Y-1: ypos=ypos+1 - elif c==curses.KEY_LEFT and xpos>0: xpos=xpos-1 - elif c==curses.KEY_RIGHT and xpos<board.X-1: xpos=xpos+1 - else: pass # Ignore incorrect keys - -if __name__=='__main__': - try: - # Initialize curses - stdscr=curses.initscr() - # Turn off echoing of keys, and enter cbreak mode, - # where no buffering is performed on keyboard input - curses.noecho() ; curses.cbreak() - - # In keypad mode, escape sequences for special keys - # (like the cursor keys) will be interpreted and - # a special value like curses.KEY_LEFT will be returned - stdscr.keypad(1) - main(stdscr) # Enter the main loop - # Set everything back to normal - stdscr.keypad(0) - curses.echo() ; curses.nocbreak() - curses.endwin() # Terminate curses - except: - # In the event of an error, restore the terminal - # to a sane state. - stdscr.keypad(0) - curses.echo() ; curses.nocbreak() - curses.endwin() - traceback.print_exc() # Print the exception + elif c == curses.KEY_UP and ypos>0: ypos -= 1 + elif c == curses.KEY_DOWN and ypos<board.Y-1: ypos += 1 + elif c == curses.KEY_LEFT and xpos>0: xpos -= 1 + elif c == curses.KEY_RIGHT and xpos<board.X-1: xpos += 1 + else: + # Ignore incorrect keys + pass + + +def main(stdscr): + keyloop(stdscr) # Enter the main loop + + +if __name__ == '__main__': + curses.wrapper(main) diff --git a/Demo/curses/rain.py b/Demo/curses/rain.py index 69794b3..9d46e6e 100644 --- a/Demo/curses/rain.py +++ b/Demo/curses/rain.py @@ -48,7 +48,7 @@ def main(win): ypos[j] = randrange(0, r) + 2 j = 0 - while 1: + while True: x = randrange(0, c) + 2 y = randrange(0, r) + 2 @@ -83,7 +83,7 @@ def main(win): ch = stdscr.getch() if ch == ord('q') or ch == ord('Q'): - return 0 + return elif ch == ord('s'): stdscr.nodelay(0) elif ch == ord(' '): diff --git a/Demo/curses/repeat.py b/Demo/curses/repeat.py index 158264c..fa7daac 100755 --- a/Demo/curses/repeat.py +++ b/Demo/curses/repeat.py @@ -2,7 +2,7 @@ """repeat <shell-command> -This simple program repeatedly (with 1-second intervals) executes the +This simple program repeatedly (at 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 @@ -38,7 +38,7 @@ def main(): sys.exit(sts) w = curses.initscr() try: - while 1: + while True: w.erase() try: w.addstr(text) diff --git a/Demo/curses/tclock.py b/Demo/curses/tclock.py index 1950043..8058d9a 100644 --- a/Demo/curses/tclock.py +++ b/Demo/curses/tclock.py @@ -14,7 +14,8 @@ def sign(_x): return 1 def A2XY(angle, radius): - return int(round(ASPECT * radius * sin(angle))), int(round(radius * cos(angle))) + return (int(round(ASPECT * radius * sin(angle))), + int(round(radius * cos(angle)))) def plot(x, y, col): stdscr.addch(y, x, col) @@ -37,9 +38,9 @@ def dline(pair, from_x, from_y, x2, y2, ch): y = from_y if ax > ay: - d = ay - ax / 2 + d = ay - ax // 2 - while 1: + while True: plot(x, y, ch) if x == x2: return @@ -50,9 +51,9 @@ def dline(pair, from_x, from_y, x2, y2, ch): x += sx d += ay else: - d = ax - ay / 2 + d = ax - ay // 2 - while 1: + while True: plot(x, y, ch) if y == y2: return @@ -78,12 +79,12 @@ def main(win): 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 + 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 @@ -96,7 +97,7 @@ def main(win): sradius = max(sradius-4, 8) - while 1: + while True: curses.napms(1000) tim = time.time() diff --git a/Demo/curses/xmas.py b/Demo/curses/xmas.py index e51bc5f..349b3a8 100644 --- a/Demo/curses/xmas.py +++ b/Demo/curses/xmas.py @@ -4,7 +4,7 @@ # $Id$ # # I'm dreaming of an ascii character-based monochrome Christmas, -# Just like the one's I used to know! +# Just like the ones I used to know! # Via a full duplex communications channel, # At 9600 bits per second, # Even though it's kinda slow. @@ -272,7 +272,7 @@ def strng5(): def blinkit(): treescrn8.touchwin() - for cycle in range(0, 5): + for cycle in range(5): if cycle == 0: treescrn3.overlay(treescrn8) treescrn8.refresh() @@ -380,7 +380,7 @@ def reindeer(): middeer0.refresh() w_del_msg.refresh() - for looper in range(0, 2): + for looper in range(2): deer_step(middeer3, y_pos, x_pos) deer_step(middeer2, y_pos, x_pos) deer_step(middeer1, y_pos, x_pos) diff --git a/Demo/sockets/README b/Demo/sockets/README index 21ed808..f5405ab 100644 --- a/Demo/sockets/README +++ b/Demo/sockets/README @@ -19,4 +19,3 @@ 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/unixclient.py b/Demo/sockets/unixclient.py index cccd617..fdbcc7a 100644 --- a/Demo/sockets/unixclient.py +++ b/Demo/sockets/unixclient.py @@ -1,7 +1,9 @@ # Echo client demo using Unix sockets # Piet van Oostrum + from socket import * -FILE = 'blabla' + +FILE = 'unix-socket' s = socket(AF_UNIX, SOCK_STREAM) s.connect(FILE) s.send('Hello, world') diff --git a/Demo/sockets/unixserver.py b/Demo/sockets/unixserver.py index 5eccabb..b73f857 100644 --- a/Demo/sockets/unixserver.py +++ b/Demo/sockets/unixserver.py @@ -1,17 +1,24 @@ # Echo server demo using Unix sockets (handles one connection only) # Piet van Oostrum + import os from socket import * -FILE = 'blabla' + +FILE = 'unix-socket' s = socket(AF_UNIX, SOCK_STREAM) s.bind(FILE) + print 'Sock name is: ['+s.getsockname()+']' + +# Wait for a connection s.listen(1) conn, addr = s.accept() -print 'Connected by', addr -while 1: + +while True: data = conn.recv(1024) - if not data: break + if not data: + break conn.send(data) + conn.close() os.unlink(FILE) diff --git a/Demo/threads/fcmp.py b/Demo/threads/fcmp.py index 83ebe01..27af76d 100644 --- a/Demo/threads/fcmp.py +++ b/Demo/threads/fcmp.py @@ -4,14 +4,14 @@ 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 ): +def fringe(co, list): for x in list: if type(x) is type([]): fringe(co, x) else: co.back(x) -def printinorder( list ): +def printinorder(list): co = Coroutine() f = co.create(fringe, co, list) try: @@ -27,7 +27,7 @@ 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 ): +def fcmp(l1, l2): co1 = Coroutine(); f1 = co1.create(fringe, co1, l1) co2 = Coroutine(); f2 = co2.create(fringe, co2, l2) while 1: diff --git a/Demo/xmlrpc/xmlrpc_handler.py b/Demo/xmlrpc/xmlrpc_handler.py deleted file mode 100644 index 359d6f1..0000000 --- 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.lower() 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 7af73be..0000000 --- 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 index e2801de..87fed4a 100755 --- a/Demo/zlib/minigzip.py +++ b/Demo/zlib/minigzip.py @@ -1,106 +1,133 @@ #!/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. +# +# The 'gzip' module in the standard library provides a more complete +# implementation of gzip-format files. + +import zlib, sys, os 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)) ; 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) + v = ord(input.read(1)) + v += (ord(input.read(1)) << 8 ) + v += (ord(input.read(1)) << 16) + v += (ord(input.read(1)) << 24) return v -import zlib, sys -if len(sys.argv)!=2: - print 'Usage: minigzip.py <filename>' - 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: +def compress (filename, input, output): 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] + statval = os.stat(filename) # ... modification time ... + 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, + 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) + while True: + 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)) +def decompress (input, output): + 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)) + xlen = ord(input.read(1)) + 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 + while True: + s = input.read(1) + if s == '\0': break if flag & FCOMMENT: # Read and discard a null-terminated string containing a comment - while (1): + while True: s=input.read(1) - if s=='\000': break + if s=='\0': 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): + + decompobj = zlib.decompressobj(-zlib.MAX_WBITS) + crcval = zlib.crc32("") + length = 0 + while True: 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) + if data == "": + break + decompdata = decompobj.decompress(data) + output.write(decompdata) + length += len(decompdata) + crcval = zlib.crc32(decompdata, crcval) + + decompdata = decompobj.flush() + output.write(decompdata) + 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' + crc32 = read32(input) + isize = read32(input) + if crc32 != crcval: + print 'CRC check failed.' + if isize != length: + print 'Incorrect length of data produced' + +def main(): + if len(sys.argv)!=2: + print 'Usage: minigzip.py <filename>' + print ' The file will be compressed or decompressed.' + sys.exit(0) + + filename = sys.argv[1] + if filename.endswith('.gz'): + compressing = False + outputname = filename[:-3] + else: + compressing = True + outputname = filename + '.gz' + + input = open(filename, 'rb') + output = open(outputname, 'wb') + + if compressing: + compress(filename, input, output) + else: + decompress(input, output) + + input.close() + output.close() -input.close() ; output.close() +if __name__ == '__main__': + main() diff --git a/Demo/zlib/zlibdemo.py b/Demo/zlib/zlibdemo.py index 5a0ab63..b449c19 100755 --- a/Demo/zlib/zlibdemo.py +++ b/Demo/zlib/zlibdemo.py @@ -1,35 +1,48 @@ #!/usr/bin/env python +# Takes an optional filename, defaulting to this file itself. +# Reads the file and compresses the content using level 1 and level 9 +# compression, printing a summary of the results. + 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) + +def main(): + if len(sys.argv) > 1: + filename = sys.argv[1] + else: + filename = sys.argv[0] + print 'Reading', filename + + f = open(filename, 'rb') # 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]) + # Don't forget to call flush()!! + comptext = comptext + compressor.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) + +if __name__ == '__main__': + main() |