/Lib/pipes.py

http://unladen-swallow.googlecode.com/ · Python · 282 lines · 219 code · 17 blank · 46 comment · 21 complexity · bddc74f34d96b3999939bfc866dee126 MD5 · raw file

  1. """Conversion pipeline templates.
  2. The problem:
  3. ------------
  4. Suppose you have some data that you want to convert to another format,
  5. such as from GIF image format to PPM image format. Maybe the
  6. conversion involves several steps (e.g. piping it through compress or
  7. uuencode). Some of the conversion steps may require that their input
  8. is a disk file, others may be able to read standard input; similar for
  9. their output. The input to the entire conversion may also be read
  10. from a disk file or from an open file, and similar for its output.
  11. The module lets you construct a pipeline template by sticking one or
  12. more conversion steps together. It will take care of creating and
  13. removing temporary files if they are necessary to hold intermediate
  14. data. You can then use the template to do conversions from many
  15. different sources to many different destinations. The temporary
  16. file names used are different each time the template is used.
  17. The templates are objects so you can create templates for many
  18. different conversion steps and store them in a dictionary, for
  19. instance.
  20. Directions:
  21. -----------
  22. To create a template:
  23. t = Template()
  24. To add a conversion step to a template:
  25. t.append(command, kind)
  26. where kind is a string of two characters: the first is '-' if the
  27. command reads its standard input or 'f' if it requires a file; the
  28. second likewise for the output. The command must be valid /bin/sh
  29. syntax. If input or output files are required, they are passed as
  30. $IN and $OUT; otherwise, it must be possible to use the command in
  31. a pipeline.
  32. To add a conversion step at the beginning:
  33. t.prepend(command, kind)
  34. To convert a file to another file using a template:
  35. sts = t.copy(infile, outfile)
  36. If infile or outfile are the empty string, standard input is read or
  37. standard output is written, respectively. The return value is the
  38. exit status of the conversion pipeline.
  39. To open a file for reading or writing through a conversion pipeline:
  40. fp = t.open(file, mode)
  41. where mode is 'r' to read the file, or 'w' to write it -- just like
  42. for the built-in function open() or for os.popen().
  43. To create a new template object initialized to a given one:
  44. t2 = t.clone()
  45. For an example, see the function test() at the end of the file.
  46. """ # '
  47. import re
  48. import os
  49. import tempfile
  50. import string
  51. __all__ = ["Template"]
  52. # Conversion step kinds
  53. FILEIN_FILEOUT = 'ff' # Must read & write real files
  54. STDIN_FILEOUT = '-f' # Must write a real file
  55. FILEIN_STDOUT = 'f-' # Must read a real file
  56. STDIN_STDOUT = '--' # Normal pipeline element
  57. SOURCE = '.-' # Must be first, writes stdout
  58. SINK = '-.' # Must be last, reads stdin
  59. stepkinds = [FILEIN_FILEOUT, STDIN_FILEOUT, FILEIN_STDOUT, STDIN_STDOUT, \
  60. SOURCE, SINK]
  61. class Template:
  62. """Class representing a pipeline template."""
  63. def __init__(self):
  64. """Template() returns a fresh pipeline template."""
  65. self.debugging = 0
  66. self.reset()
  67. def __repr__(self):
  68. """t.__repr__() implements repr(t)."""
  69. return '<Template instance, steps=%r>' % (self.steps,)
  70. def reset(self):
  71. """t.reset() restores a pipeline template to its initial state."""
  72. self.steps = []
  73. def clone(self):
  74. """t.clone() returns a new pipeline template with identical
  75. initial state as the current one."""
  76. t = Template()
  77. t.steps = self.steps[:]
  78. t.debugging = self.debugging
  79. return t
  80. def debug(self, flag):
  81. """t.debug(flag) turns debugging on or off."""
  82. self.debugging = flag
  83. def append(self, cmd, kind):
  84. """t.append(cmd, kind) adds a new step at the end."""
  85. if type(cmd) is not type(''):
  86. raise TypeError, \
  87. 'Template.append: cmd must be a string'
  88. if kind not in stepkinds:
  89. raise ValueError, \
  90. 'Template.append: bad kind %r' % (kind,)
  91. if kind == SOURCE:
  92. raise ValueError, \
  93. 'Template.append: SOURCE can only be prepended'
  94. if self.steps and self.steps[-1][1] == SINK:
  95. raise ValueError, \
  96. 'Template.append: already ends with SINK'
  97. if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
  98. raise ValueError, \
  99. 'Template.append: missing $IN in cmd'
  100. if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
  101. raise ValueError, \
  102. 'Template.append: missing $OUT in cmd'
  103. self.steps.append((cmd, kind))
  104. def prepend(self, cmd, kind):
  105. """t.prepend(cmd, kind) adds a new step at the front."""
  106. if type(cmd) is not type(''):
  107. raise TypeError, \
  108. 'Template.prepend: cmd must be a string'
  109. if kind not in stepkinds:
  110. raise ValueError, \
  111. 'Template.prepend: bad kind %r' % (kind,)
  112. if kind == SINK:
  113. raise ValueError, \
  114. 'Template.prepend: SINK can only be appended'
  115. if self.steps and self.steps[0][1] == SOURCE:
  116. raise ValueError, \
  117. 'Template.prepend: already begins with SOURCE'
  118. if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
  119. raise ValueError, \
  120. 'Template.prepend: missing $IN in cmd'
  121. if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
  122. raise ValueError, \
  123. 'Template.prepend: missing $OUT in cmd'
  124. self.steps.insert(0, (cmd, kind))
  125. def open(self, file, rw):
  126. """t.open(file, rw) returns a pipe or file object open for
  127. reading or writing; the file is the other end of the pipeline."""
  128. if rw == 'r':
  129. return self.open_r(file)
  130. if rw == 'w':
  131. return self.open_w(file)
  132. raise ValueError, \
  133. 'Template.open: rw must be \'r\' or \'w\', not %r' % (rw,)
  134. def open_r(self, file):
  135. """t.open_r(file) and t.open_w(file) implement
  136. t.open(file, 'r') and t.open(file, 'w') respectively."""
  137. if not self.steps:
  138. return open(file, 'r')
  139. if self.steps[-1][1] == SINK:
  140. raise ValueError, \
  141. 'Template.open_r: pipeline ends width SINK'
  142. cmd = self.makepipeline(file, '')
  143. return os.popen(cmd, 'r')
  144. def open_w(self, file):
  145. if not self.steps:
  146. return open(file, 'w')
  147. if self.steps[0][1] == SOURCE:
  148. raise ValueError, \
  149. 'Template.open_w: pipeline begins with SOURCE'
  150. cmd = self.makepipeline('', file)
  151. return os.popen(cmd, 'w')
  152. def copy(self, infile, outfile):
  153. return os.system(self.makepipeline(infile, outfile))
  154. def makepipeline(self, infile, outfile):
  155. cmd = makepipeline(infile, self.steps, outfile)
  156. if self.debugging:
  157. print cmd
  158. cmd = 'set -x; ' + cmd
  159. return cmd
  160. def makepipeline(infile, steps, outfile):
  161. # Build a list with for each command:
  162. # [input filename or '', command string, kind, output filename or '']
  163. list = []
  164. for cmd, kind in steps:
  165. list.append(['', cmd, kind, ''])
  166. #
  167. # Make sure there is at least one step
  168. #
  169. if not list:
  170. list.append(['', 'cat', '--', ''])
  171. #
  172. # Take care of the input and output ends
  173. #
  174. [cmd, kind] = list[0][1:3]
  175. if kind[0] == 'f' and not infile:
  176. list.insert(0, ['', 'cat', '--', ''])
  177. list[0][0] = infile
  178. #
  179. [cmd, kind] = list[-1][1:3]
  180. if kind[1] == 'f' and not outfile:
  181. list.append(['', 'cat', '--', ''])
  182. list[-1][-1] = outfile
  183. #
  184. # Invent temporary files to connect stages that need files
  185. #
  186. garbage = []
  187. for i in range(1, len(list)):
  188. lkind = list[i-1][2]
  189. rkind = list[i][2]
  190. if lkind[1] == 'f' or rkind[0] == 'f':
  191. (fd, temp) = tempfile.mkstemp()
  192. os.close(fd)
  193. garbage.append(temp)
  194. list[i-1][-1] = list[i][0] = temp
  195. #
  196. for item in list:
  197. [inf, cmd, kind, outf] = item
  198. if kind[1] == 'f':
  199. cmd = 'OUT=' + quote(outf) + '; ' + cmd
  200. if kind[0] == 'f':
  201. cmd = 'IN=' + quote(inf) + '; ' + cmd
  202. if kind[0] == '-' and inf:
  203. cmd = cmd + ' <' + quote(inf)
  204. if kind[1] == '-' and outf:
  205. cmd = cmd + ' >' + quote(outf)
  206. item[1] = cmd
  207. #
  208. cmdlist = list[0][1]
  209. for item in list[1:]:
  210. [cmd, kind] = item[1:3]
  211. if item[0] == '':
  212. if 'f' in kind:
  213. cmd = '{ ' + cmd + '; }'
  214. cmdlist = cmdlist + ' |\n' + cmd
  215. else:
  216. cmdlist = cmdlist + '\n' + cmd
  217. #
  218. if garbage:
  219. rmcmd = 'rm -f'
  220. for file in garbage:
  221. rmcmd = rmcmd + ' ' + quote(file)
  222. trapcmd = 'trap ' + quote(rmcmd + '; exit') + ' 1 2 3 13 14 15'
  223. cmdlist = trapcmd + '\n' + cmdlist + '\n' + rmcmd
  224. #
  225. return cmdlist
  226. # Reliably quote a string as a single argument for /bin/sh
  227. _safechars = string.ascii_letters + string.digits + '!@%_-+=:,./' # Safe unquoted
  228. _funnychars = '"`$\\' # Unsafe inside "double quotes"
  229. def quote(file):
  230. for c in file:
  231. if c not in _safechars:
  232. break
  233. else:
  234. return file
  235. if '\'' not in file:
  236. return '\'' + file + '\''
  237. res = ''
  238. for c in file:
  239. if c in _funnychars:
  240. c = '\\' + c
  241. res = res + c
  242. return '"' + res + '"'