pipes.py 9.4 KB

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