pipes.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. """ # '
  46. import re
  47. import os
  48. import tempfile
  49. # we import the quote function rather than the module for backward compat
  50. # (quote used to be an undocumented but used function in pipes)
  51. from shlex import quote
  52. __all__ = ["Template"]
  53. # Conversion step kinds
  54. FILEIN_FILEOUT = 'ff' # Must read & write real files
  55. STDIN_FILEOUT = '-f' # Must write a real file
  56. FILEIN_STDOUT = 'f-' # Must read a real file
  57. STDIN_STDOUT = '--' # Normal pipeline element
  58. SOURCE = '.-' # Must be first, writes stdout
  59. SINK = '-.' # Must be last, reads stdin
  60. stepkinds = [FILEIN_FILEOUT, STDIN_FILEOUT, FILEIN_STDOUT, STDIN_STDOUT, \
  61. SOURCE, SINK]
  62. class Template:
  63. """Class representing a pipeline template."""
  64. def __init__(self):
  65. """Template() returns a fresh pipeline template."""
  66. self.debugging = 0
  67. self.reset()
  68. def __repr__(self):
  69. """t.__repr__() implements repr(t)."""
  70. return '<Template instance, steps=%r>' % (self.steps,)
  71. def reset(self):
  72. """t.reset() restores a pipeline template to its initial state."""
  73. self.steps = []
  74. def clone(self):
  75. """t.clone() returns a new pipeline template with identical
  76. initial state as the current one."""
  77. t = Template()
  78. t.steps = self.steps[:]
  79. t.debugging = self.debugging
  80. return t
  81. def debug(self, flag):
  82. """t.debug(flag) turns debugging on or off."""
  83. self.debugging = flag
  84. def append(self, cmd, kind):
  85. """t.append(cmd, kind) adds a new step at the end."""
  86. if type(cmd) is not type(''):
  87. raise TypeError('Template.append: cmd must be a string')
  88. if kind not in stepkinds:
  89. raise ValueError('Template.append: bad kind %r' % (kind,))
  90. if kind == SOURCE:
  91. raise ValueError('Template.append: SOURCE can only be prepended')
  92. if self.steps and self.steps[-1][1] == SINK:
  93. raise ValueError('Template.append: already ends with SINK')
  94. if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
  95. raise ValueError('Template.append: missing $IN in cmd')
  96. if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
  97. raise ValueError('Template.append: missing $OUT in cmd')
  98. self.steps.append((cmd, kind))
  99. def prepend(self, cmd, kind):
  100. """t.prepend(cmd, kind) adds a new step at the front."""
  101. if type(cmd) is not type(''):
  102. raise TypeError('Template.prepend: cmd must be a string')
  103. if kind not in stepkinds:
  104. raise ValueError('Template.prepend: bad kind %r' % (kind,))
  105. if kind == SINK:
  106. raise ValueError('Template.prepend: SINK can only be appended')
  107. if self.steps and self.steps[0][1] == SOURCE:
  108. raise ValueError('Template.prepend: already begins with SOURCE')
  109. if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
  110. raise ValueError('Template.prepend: missing $IN in cmd')
  111. if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
  112. raise ValueError('Template.prepend: missing $OUT in cmd')
  113. self.steps.insert(0, (cmd, kind))
  114. def open(self, file, rw):
  115. """t.open(file, rw) returns a pipe or file object open for
  116. reading or writing; the file is the other end of the pipeline."""
  117. if rw == 'r':
  118. return self.open_r(file)
  119. if rw == 'w':
  120. return self.open_w(file)
  121. raise ValueError('Template.open: rw must be \'r\' or \'w\', not %r'
  122. % (rw,))
  123. def open_r(self, file):
  124. """t.open_r(file) and t.open_w(file) implement
  125. t.open(file, 'r') and t.open(file, 'w') respectively."""
  126. if not self.steps:
  127. return open(file, 'r')
  128. if self.steps[-1][1] == SINK:
  129. raise ValueError('Template.open_r: pipeline ends width SINK')
  130. cmd = self.makepipeline(file, '')
  131. return os.popen(cmd, 'r')
  132. def open_w(self, file):
  133. if not self.steps:
  134. return open(file, 'w')
  135. if self.steps[0][1] == SOURCE:
  136. raise ValueError('Template.open_w: pipeline begins with SOURCE')
  137. cmd = self.makepipeline('', file)
  138. return os.popen(cmd, 'w')
  139. def copy(self, infile, outfile):
  140. return os.system(self.makepipeline(infile, outfile))
  141. def makepipeline(self, infile, outfile):
  142. cmd = makepipeline(infile, self.steps, outfile)
  143. if self.debugging:
  144. print(cmd)
  145. cmd = 'set -x; ' + cmd
  146. return cmd
  147. def makepipeline(infile, steps, outfile):
  148. # Build a list with for each command:
  149. # [input filename or '', command string, kind, output filename or '']
  150. list = []
  151. for cmd, kind in steps:
  152. list.append(['', cmd, kind, ''])
  153. #
  154. # Make sure there is at least one step
  155. #
  156. if not list:
  157. list.append(['', 'cat', '--', ''])
  158. #
  159. # Take care of the input and output ends
  160. #
  161. [cmd, kind] = list[0][1:3]
  162. if kind[0] == 'f' and not infile:
  163. list.insert(0, ['', 'cat', '--', ''])
  164. list[0][0] = infile
  165. #
  166. [cmd, kind] = list[-1][1:3]
  167. if kind[1] == 'f' and not outfile:
  168. list.append(['', 'cat', '--', ''])
  169. list[-1][-1] = outfile
  170. #
  171. # Invent temporary files to connect stages that need files
  172. #
  173. garbage = []
  174. for i in range(1, len(list)):
  175. lkind = list[i-1][2]
  176. rkind = list[i][2]
  177. if lkind[1] == 'f' or rkind[0] == 'f':
  178. (fd, temp) = tempfile.mkstemp()
  179. os.close(fd)
  180. garbage.append(temp)
  181. list[i-1][-1] = list[i][0] = temp
  182. #
  183. for item in list:
  184. [inf, cmd, kind, outf] = item
  185. if kind[1] == 'f':
  186. cmd = 'OUT=' + quote(outf) + '; ' + cmd
  187. if kind[0] == 'f':
  188. cmd = 'IN=' + quote(inf) + '; ' + cmd
  189. if kind[0] == '-' and inf:
  190. cmd = cmd + ' <' + quote(inf)
  191. if kind[1] == '-' and outf:
  192. cmd = cmd + ' >' + quote(outf)
  193. item[1] = cmd
  194. #
  195. cmdlist = list[0][1]
  196. for item in list[1:]:
  197. [cmd, kind] = item[1:3]
  198. if item[0] == '':
  199. if 'f' in kind:
  200. cmd = '{ ' + cmd + '; }'
  201. cmdlist = cmdlist + ' |\n' + cmd
  202. else:
  203. cmdlist = cmdlist + '\n' + cmd
  204. #
  205. if garbage:
  206. rmcmd = 'rm -f'
  207. for file in garbage:
  208. rmcmd = rmcmd + ' ' + quote(file)
  209. trapcmd = 'trap ' + quote(rmcmd + '; exit') + ' 1 2 3 13 14 15'
  210. cmdlist = trapcmd + '\n' + cmdlist + '\n' + rmcmd
  211. #
  212. return cmdlist