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