Ditched '_find_SET()', since it was a no-value-added wrapper around
[python/dscho.git] / Lib / base64.py
blob5ef2081c881a5be14cec1872234e116ddb77bc7d
1 #! /usr/bin/env python
3 """Conversions to/from base64 transport encoding as per RFC-1521."""
5 # Modified 04-Oct-95 by Jack to use binascii module
7 import binascii
9 MAXLINESIZE = 76 # Excluding the CRLF
10 MAXBINSIZE = (MAXLINESIZE/4)*3
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)
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)
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()
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()
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: basd64 [-d] [-e] [-u] [-t] [file|-]
57 -d, -u: decode
58 -e: encode (default)
59 -t: decode string 'Aladdin:open sesame'"""
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)
72 def test1():
73 s0 = "Aladdin:open sesame"
74 s1 = encodestring(s0)
75 s2 = decodestring(s1)
76 print s0, `s1`, s2
78 if __name__ == '__main__':
79 test()