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