/Lib/uu.py

http://unladen-swallow.googlecode.com/ · Python · 186 lines · 115 code · 14 blank · 57 comment · 46 complexity · be218390eea294156c164df7165b249a MD5 · raw file

  1. #! /usr/bin/env python
  2. # Copyright 1994 by Lance Ellinghouse
  3. # Cathedral City, California Republic, United States of America.
  4. # All Rights Reserved
  5. # Permission to use, copy, modify, and distribute this software and its
  6. # documentation for any purpose and without fee is hereby granted,
  7. # provided that the above copyright notice appear in all copies and that
  8. # both that copyright notice and this permission notice appear in
  9. # supporting documentation, and that the name of Lance Ellinghouse
  10. # not be used in advertising or publicity pertaining to distribution
  11. # of the software without specific, written prior permission.
  12. # LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
  13. # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  14. # FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE
  15. # FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  16. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  17. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  18. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  19. #
  20. # Modified by Jack Jansen, CWI, July 1995:
  21. # - Use binascii module to do the actual line-by-line conversion
  22. # between ascii and binary. This results in a 1000-fold speedup. The C
  23. # version is still 5 times faster, though.
  24. # - Arguments more compliant with python standard
  25. """Implementation of the UUencode and UUdecode functions.
  26. encode(in_file, out_file [,name, mode])
  27. decode(in_file [, out_file, mode])
  28. """
  29. import binascii
  30. import os
  31. import sys
  32. __all__ = ["Error", "encode", "decode"]
  33. class Error(Exception):
  34. pass
  35. def encode(in_file, out_file, name=None, mode=None):
  36. """Uuencode file"""
  37. #
  38. # If in_file is a pathname open it and change defaults
  39. #
  40. if in_file == '-':
  41. in_file = sys.stdin
  42. elif isinstance(in_file, basestring):
  43. if name is None:
  44. name = os.path.basename(in_file)
  45. if mode is None:
  46. try:
  47. mode = os.stat(in_file).st_mode
  48. except AttributeError:
  49. pass
  50. in_file = open(in_file, 'rb')
  51. #
  52. # Open out_file if it is a pathname
  53. #
  54. if out_file == '-':
  55. out_file = sys.stdout
  56. elif isinstance(out_file, basestring):
  57. out_file = open(out_file, 'w')
  58. #
  59. # Set defaults for name and mode
  60. #
  61. if name is None:
  62. name = '-'
  63. if mode is None:
  64. mode = 0666
  65. #
  66. # Write the data
  67. #
  68. out_file.write('begin %o %s\n' % ((mode&0777),name))
  69. data = in_file.read(45)
  70. while len(data) > 0:
  71. out_file.write(binascii.b2a_uu(data))
  72. data = in_file.read(45)
  73. out_file.write(' \nend\n')
  74. def decode(in_file, out_file=None, mode=None, quiet=0):
  75. """Decode uuencoded file"""
  76. #
  77. # Open the input file, if needed.
  78. #
  79. if in_file == '-':
  80. in_file = sys.stdin
  81. elif isinstance(in_file, basestring):
  82. in_file = open(in_file)
  83. #
  84. # Read until a begin is encountered or we've exhausted the file
  85. #
  86. while True:
  87. hdr = in_file.readline()
  88. if not hdr:
  89. raise Error('No valid begin line found in input file')
  90. if not hdr.startswith('begin'):
  91. continue
  92. hdrfields = hdr.split(' ', 2)
  93. if len(hdrfields) == 3 and hdrfields[0] == 'begin':
  94. try:
  95. int(hdrfields[1], 8)
  96. break
  97. except ValueError:
  98. pass
  99. if out_file is None:
  100. out_file = hdrfields[2].rstrip()
  101. if os.path.exists(out_file):
  102. raise Error('Cannot overwrite existing file: %s' % out_file)
  103. if mode is None:
  104. mode = int(hdrfields[1], 8)
  105. #
  106. # Open the output file
  107. #
  108. opened = False
  109. if out_file == '-':
  110. out_file = sys.stdout
  111. elif isinstance(out_file, basestring):
  112. fp = open(out_file, 'wb')
  113. try:
  114. os.path.chmod(out_file, mode)
  115. except AttributeError:
  116. pass
  117. out_file = fp
  118. opened = True
  119. #
  120. # Main decoding loop
  121. #
  122. s = in_file.readline()
  123. while s and s.strip() != 'end':
  124. try:
  125. data = binascii.a2b_uu(s)
  126. except binascii.Error, v:
  127. # Workaround for broken uuencoders by /Fredrik Lundh
  128. nbytes = (((ord(s[0])-32) & 63) * 4 + 5) // 3
  129. data = binascii.a2b_uu(s[:nbytes])
  130. if not quiet:
  131. sys.stderr.write("Warning: %s\n" % v)
  132. out_file.write(data)
  133. s = in_file.readline()
  134. if not s:
  135. raise Error('Truncated input file')
  136. if opened:
  137. out_file.close()
  138. def test():
  139. """uuencode/uudecode main program"""
  140. import optparse
  141. parser = optparse.OptionParser(usage='usage: %prog [-d] [-t] [input [output]]')
  142. parser.add_option('-d', '--decode', dest='decode', help='Decode (instead of encode)?', default=False, action='store_true')
  143. parser.add_option('-t', '--text', dest='text', help='data is text, encoded format unix-compatible text?', default=False, action='store_true')
  144. (options, args) = parser.parse_args()
  145. if len(args) > 2:
  146. parser.error('incorrect number of arguments')
  147. sys.exit(1)
  148. input = sys.stdin
  149. output = sys.stdout
  150. if len(args) > 0:
  151. input = args[0]
  152. if len(args) > 1:
  153. output = args[1]
  154. if options.decode:
  155. if options.text:
  156. if isinstance(output, basestring):
  157. output = open(output, 'w')
  158. else:
  159. print sys.argv[0], ': cannot do -t to stdout'
  160. sys.exit(1)
  161. decode(input, output)
  162. else:
  163. if options.text:
  164. if isinstance(input, basestring):
  165. input = open(input, 'r')
  166. else:
  167. print sys.argv[0], ': cannot do -t from stdin'
  168. sys.exit(1)
  169. encode(input, output)
  170. if __name__ == '__main__':
  171. test()