/Lib/fileinput.py

http://unladen-swallow.googlecode.com/ · Python · 413 lines · 373 code · 8 blank · 32 comment · 18 complexity · 05ea8fb511f3b8e65407f6a35bc041d7 MD5 · raw file

  1. """Helper class to quickly write a loop over all standard input files.
  2. Typical use is:
  3. import fileinput
  4. for line in fileinput.input():
  5. process(line)
  6. This iterates over the lines of all files listed in sys.argv[1:],
  7. defaulting to sys.stdin if the list is empty. If a filename is '-' it
  8. is also replaced by sys.stdin. To specify an alternative list of
  9. filenames, pass it as the argument to input(). A single file name is
  10. also allowed.
  11. Functions filename(), lineno() return the filename and cumulative line
  12. number of the line that has just been read; filelineno() returns its
  13. line number in the current file; isfirstline() returns true iff the
  14. line just read is the first line of its file; isstdin() returns true
  15. iff the line was read from sys.stdin. Function nextfile() closes the
  16. current file so that the next iteration will read the first line from
  17. the next file (if any); lines not read from the file will not count
  18. towards the cumulative line count; the filename is not changed until
  19. after the first line of the next file has been read. Function close()
  20. closes the sequence.
  21. Before any lines have been read, filename() returns None and both line
  22. numbers are zero; nextfile() has no effect. After all lines have been
  23. read, filename() and the line number functions return the values
  24. pertaining to the last line read; nextfile() has no effect.
  25. All files are opened in text mode by default, you can override this by
  26. setting the mode parameter to input() or FileInput.__init__().
  27. If an I/O error occurs during opening or reading a file, the IOError
  28. exception is raised.
  29. If sys.stdin is used more than once, the second and further use will
  30. return no lines, except perhaps for interactive use, or if it has been
  31. explicitly reset (e.g. using sys.stdin.seek(0)).
  32. Empty files are opened and immediately closed; the only time their
  33. presence in the list of filenames is noticeable at all is when the
  34. last file opened is empty.
  35. It is possible that the last line of a file doesn't end in a newline
  36. character; otherwise lines are returned including the trailing
  37. newline.
  38. Class FileInput is the implementation; its methods filename(),
  39. lineno(), fileline(), isfirstline(), isstdin(), nextfile() and close()
  40. correspond to the functions in the module. In addition it has a
  41. readline() method which returns the next input line, and a
  42. __getitem__() method which implements the sequence behavior. The
  43. sequence must be accessed in strictly sequential order; sequence
  44. access and readline() cannot be mixed.
  45. Optional in-place filtering: if the keyword argument inplace=1 is
  46. passed to input() or to the FileInput constructor, the file is moved
  47. to a backup file and standard output is directed to the input file.
  48. This makes it possible to write a filter that rewrites its input file
  49. in place. If the keyword argument backup=".<some extension>" is also
  50. given, it specifies the extension for the backup file, and the backup
  51. file remains around; by default, the extension is ".bak" and it is
  52. deleted when the output file is closed. In-place filtering is
  53. disabled when standard input is read. XXX The current implementation
  54. does not work for MS-DOS 8+3 filesystems.
  55. Performance: this module is unfortunately one of the slower ways of
  56. processing large numbers of input lines. Nevertheless, a significant
  57. speed-up has been obtained by using readlines(bufsize) instead of
  58. readline(). A new keyword argument, bufsize=N, is present on the
  59. input() function and the FileInput() class to override the default
  60. buffer size.
  61. XXX Possible additions:
  62. - optional getopt argument processing
  63. - isatty()
  64. - read(), read(size), even readlines()
  65. """
  66. import sys, os
  67. __all__ = ["input","close","nextfile","filename","lineno","filelineno",
  68. "isfirstline","isstdin","FileInput"]
  69. _state = None
  70. DEFAULT_BUFSIZE = 8*1024
  71. def input(files=None, inplace=0, backup="", bufsize=0,
  72. mode="r", openhook=None):
  73. """input([files[, inplace[, backup[, mode[, openhook]]]]])
  74. Create an instance of the FileInput class. The instance will be used
  75. as global state for the functions of this module, and is also returned
  76. to use during iteration. The parameters to this function will be passed
  77. along to the constructor of the FileInput class.
  78. """
  79. global _state
  80. if _state and _state._file:
  81. raise RuntimeError, "input() already active"
  82. _state = FileInput(files, inplace, backup, bufsize, mode, openhook)
  83. return _state
  84. def close():
  85. """Close the sequence."""
  86. global _state
  87. state = _state
  88. _state = None
  89. if state:
  90. state.close()
  91. def nextfile():
  92. """
  93. Close the current file so that the next iteration will read the first
  94. line from the next file (if any); lines not read from the file will
  95. not count towards the cumulative line count. The filename is not
  96. changed until after the first line of the next file has been read.
  97. Before the first line has been read, this function has no effect;
  98. it cannot be used to skip the first file. After the last line of the
  99. last file has been read, this function has no effect.
  100. """
  101. if not _state:
  102. raise RuntimeError, "no active input()"
  103. return _state.nextfile()
  104. def filename():
  105. """
  106. Return the name of the file currently being read.
  107. Before the first line has been read, returns None.
  108. """
  109. if not _state:
  110. raise RuntimeError, "no active input()"
  111. return _state.filename()
  112. def lineno():
  113. """
  114. Return the cumulative line number of the line that has just been read.
  115. Before the first line has been read, returns 0. After the last line
  116. of the last file has been read, returns the line number of that line.
  117. """
  118. if not _state:
  119. raise RuntimeError, "no active input()"
  120. return _state.lineno()
  121. def filelineno():
  122. """
  123. Return the line number in the current file. Before the first line
  124. has been read, returns 0. After the last line of the last file has
  125. been read, returns the line number of that line within the file.
  126. """
  127. if not _state:
  128. raise RuntimeError, "no active input()"
  129. return _state.filelineno()
  130. def fileno():
  131. """
  132. Return the file number of the current file. When no file is currently
  133. opened, returns -1.
  134. """
  135. if not _state:
  136. raise RuntimeError, "no active input()"
  137. return _state.fileno()
  138. def isfirstline():
  139. """
  140. Returns true the line just read is the first line of its file,
  141. otherwise returns false.
  142. """
  143. if not _state:
  144. raise RuntimeError, "no active input()"
  145. return _state.isfirstline()
  146. def isstdin():
  147. """
  148. Returns true if the last line was read from sys.stdin,
  149. otherwise returns false.
  150. """
  151. if not _state:
  152. raise RuntimeError, "no active input()"
  153. return _state.isstdin()
  154. class FileInput:
  155. """class FileInput([files[, inplace[, backup[, mode[, openhook]]]]])
  156. Class FileInput is the implementation of the module; its methods
  157. filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
  158. nextfile() and close() correspond to the functions of the same name
  159. in the module.
  160. In addition it has a readline() method which returns the next
  161. input line, and a __getitem__() method which implements the
  162. sequence behavior. The sequence must be accessed in strictly
  163. sequential order; random access and readline() cannot be mixed.
  164. """
  165. def __init__(self, files=None, inplace=0, backup="", bufsize=0,
  166. mode="r", openhook=None):
  167. if isinstance(files, basestring):
  168. files = (files,)
  169. else:
  170. if files is None:
  171. files = sys.argv[1:]
  172. if not files:
  173. files = ('-',)
  174. else:
  175. files = tuple(files)
  176. self._files = files
  177. self._inplace = inplace
  178. self._backup = backup
  179. self._bufsize = bufsize or DEFAULT_BUFSIZE
  180. self._savestdout = None
  181. self._output = None
  182. self._filename = None
  183. self._lineno = 0
  184. self._filelineno = 0
  185. self._file = None
  186. self._isstdin = False
  187. self._backupfilename = None
  188. self._buffer = []
  189. self._bufindex = 0
  190. # restrict mode argument to reading modes
  191. if mode not in ('r', 'rU', 'U', 'rb'):
  192. raise ValueError("FileInput opening mode must be one of "
  193. "'r', 'rU', 'U' and 'rb'")
  194. self._mode = mode
  195. if inplace and openhook:
  196. raise ValueError("FileInput cannot use an opening hook in inplace mode")
  197. elif openhook and not hasattr(openhook, '__call__'):
  198. raise ValueError("FileInput openhook must be callable")
  199. self._openhook = openhook
  200. def __del__(self):
  201. self.close()
  202. def close(self):
  203. self.nextfile()
  204. self._files = ()
  205. def __iter__(self):
  206. return self
  207. def next(self):
  208. try:
  209. line = self._buffer[self._bufindex]
  210. except IndexError:
  211. pass
  212. else:
  213. self._bufindex += 1
  214. self._lineno += 1
  215. self._filelineno += 1
  216. return line
  217. line = self.readline()
  218. if not line:
  219. raise StopIteration
  220. return line
  221. def __getitem__(self, i):
  222. if i != self._lineno:
  223. raise RuntimeError, "accessing lines out of order"
  224. try:
  225. return self.next()
  226. except StopIteration:
  227. raise IndexError, "end of input reached"
  228. def nextfile(self):
  229. savestdout = self._savestdout
  230. self._savestdout = 0
  231. if savestdout:
  232. sys.stdout = savestdout
  233. output = self._output
  234. self._output = 0
  235. if output:
  236. output.close()
  237. file = self._file
  238. self._file = 0
  239. if file and not self._isstdin:
  240. file.close()
  241. backupfilename = self._backupfilename
  242. self._backupfilename = 0
  243. if backupfilename and not self._backup:
  244. try: os.unlink(backupfilename)
  245. except OSError: pass
  246. self._isstdin = False
  247. self._buffer = []
  248. self._bufindex = 0
  249. def readline(self):
  250. try:
  251. line = self._buffer[self._bufindex]
  252. except IndexError:
  253. pass
  254. else:
  255. self._bufindex += 1
  256. self._lineno += 1
  257. self._filelineno += 1
  258. return line
  259. if not self._file:
  260. if not self._files:
  261. return ""
  262. self._filename = self._files[0]
  263. self._files = self._files[1:]
  264. self._filelineno = 0
  265. self._file = None
  266. self._isstdin = False
  267. self._backupfilename = 0
  268. if self._filename == '-':
  269. self._filename = '<stdin>'
  270. self._file = sys.stdin
  271. self._isstdin = True
  272. else:
  273. if self._inplace:
  274. self._backupfilename = (
  275. self._filename + (self._backup or os.extsep+"bak"))
  276. try: os.unlink(self._backupfilename)
  277. except os.error: pass
  278. # The next few lines may raise IOError
  279. os.rename(self._filename, self._backupfilename)
  280. self._file = open(self._backupfilename, self._mode)
  281. try:
  282. perm = os.fstat(self._file.fileno()).st_mode
  283. except OSError:
  284. self._output = open(self._filename, "w")
  285. else:
  286. fd = os.open(self._filename,
  287. os.O_CREAT | os.O_WRONLY | os.O_TRUNC,
  288. perm)
  289. self._output = os.fdopen(fd, "w")
  290. try:
  291. if hasattr(os, 'chmod'):
  292. os.chmod(self._filename, perm)
  293. except OSError:
  294. pass
  295. self._savestdout = sys.stdout
  296. sys.stdout = self._output
  297. else:
  298. # This may raise IOError
  299. if self._openhook:
  300. self._file = self._openhook(self._filename, self._mode)
  301. else:
  302. self._file = open(self._filename, self._mode)
  303. self._buffer = self._file.readlines(self._bufsize)
  304. self._bufindex = 0
  305. if not self._buffer:
  306. self.nextfile()
  307. # Recursive call
  308. return self.readline()
  309. def filename(self):
  310. return self._filename
  311. def lineno(self):
  312. return self._lineno
  313. def filelineno(self):
  314. return self._filelineno
  315. def fileno(self):
  316. if self._file:
  317. try:
  318. return self._file.fileno()
  319. except ValueError:
  320. return -1
  321. else:
  322. return -1
  323. def isfirstline(self):
  324. return self._filelineno == 1
  325. def isstdin(self):
  326. return self._isstdin
  327. def hook_compressed(filename, mode):
  328. ext = os.path.splitext(filename)[1]
  329. if ext == '.gz':
  330. import gzip
  331. return gzip.open(filename, mode)
  332. elif ext == '.bz2':
  333. import bz2
  334. return bz2.BZ2File(filename, mode)
  335. else:
  336. return open(filename, mode)
  337. def hook_encoded(encoding):
  338. import codecs
  339. def openhook(filename, mode):
  340. return codecs.open(filename, mode, encoding)
  341. return openhook
  342. def _test():
  343. import getopt
  344. inplace = 0
  345. backup = 0
  346. opts, args = getopt.getopt(sys.argv[1:], "ib:")
  347. for o, a in opts:
  348. if o == '-i': inplace = 1
  349. if o == '-b': backup = a
  350. for line in input(args, inplace=inplace, backup=backup):
  351. if line[-1:] == '\n': line = line[:-1]
  352. if line[-1:] == '\r': line = line[:-1]
  353. print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
  354. isfirstline() and "*" or "", line)
  355. print "%d: %s[%d]" % (lineno(), filename(), filelineno())
  356. if __name__ == '__main__':
  357. _test()