home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / BASE64.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  2.0 KB  |  80 lines

  1. #! /usr/bin/env python
  2.  
  3. """Conversions to/from base64 transport encoding as per RFC-1521."""
  4.  
  5. # Modified 04-Oct-95 by Jack to use binascii module
  6.  
  7. import binascii
  8.  
  9. MAXLINESIZE = 76 # Excluding the CRLF
  10. MAXBINSIZE = (MAXLINESIZE/4)*3
  11.  
  12. def encode(input, output):
  13.     """Encode a file."""
  14.     while 1:
  15.         s = input.read(MAXBINSIZE)
  16.         if not s: break
  17.         while len(s) < MAXBINSIZE:
  18.             ns = input.read(MAXBINSIZE-len(s))
  19.             if not ns: break
  20.             s = s + ns
  21.         line = binascii.b2a_base64(s)
  22.         output.write(line)
  23.  
  24. def decode(input, output):
  25.     """Decode a file."""
  26.     while 1:
  27.         line = input.readline()
  28.         if not line: break
  29.         s = binascii.a2b_base64(line)
  30.         output.write(s)
  31.  
  32. def encodestring(s):
  33.     """Encode a string."""
  34.     import StringIO
  35.     f = StringIO.StringIO(s)
  36.     g = StringIO.StringIO()
  37.     encode(f, g)
  38.     return g.getvalue()
  39.  
  40. def decodestring(s):
  41.     """Decode a string."""
  42.     import StringIO
  43.     f = StringIO.StringIO(s)
  44.     g = StringIO.StringIO()
  45.     decode(f, g)
  46.     return g.getvalue()
  47.  
  48. def test():
  49.     """Small test program"""
  50.     import sys, getopt
  51.     try:
  52.         opts, args = getopt.getopt(sys.argv[1:], 'deut')
  53.     except getopt.error, msg:
  54.         sys.stdout = sys.stderr
  55.         print msg
  56.         print """usage: %s [-d|-e|-u|-t] [file|-]
  57.         -d, -u: decode
  58.         -e: encode (default)
  59.         -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]
  60.         sys.exit(2)
  61.     func = encode
  62.     for o, a in opts:
  63.         if o == '-e': func = encode
  64.         if o == '-d': func = decode
  65.         if o == '-u': func = decode
  66.         if o == '-t': test1(); return
  67.     if args and args[0] != '-':
  68.         func(open(args[0], 'rb'), sys.stdout)
  69.     else:
  70.         func(sys.stdin, sys.stdout)
  71.  
  72. def test1():
  73.     s0 = "Aladdin:open sesame"
  74.     s1 = encodestring(s0)
  75.     s2 = decodestring(s1)
  76.     print s0, `s1`, s2
  77.  
  78. if __name__ == '__main__':
  79.     test()
  80.