fileinput.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. XXX Possible additions:
  56. - optional getopt argument processing
  57. - isatty()
  58. - read(), read(size), even readlines()
  59. """
  60. import sys, os
  61. __all__ = ["input","close","nextfile","filename","lineno","filelineno",
  62. "isfirstline","isstdin","FileInput"]
  63. _state = None
  64. # No longer used
  65. DEFAULT_BUFSIZE = 8*1024
  66. def input(files=None, inplace=0, backup="", bufsize=0,
  67. mode="r", openhook=None):
  68. """Return an instance of the FileInput class, which can be iterated.
  69. The parameters are passed to the constructor of the FileInput class.
  70. The returned instance, in addition to being an iterator,
  71. keeps global state for the functions of this module,.
  72. """
  73. global _state
  74. if _state and _state._file:
  75. raise RuntimeError, "input() already active"
  76. _state = FileInput(files, inplace, backup, bufsize, mode, openhook)
  77. return _state
  78. def close():
  79. """Close the sequence."""
  80. global _state
  81. state = _state
  82. _state = None
  83. if state:
  84. state.close()
  85. def nextfile():
  86. """
  87. Close the current file so that the next iteration will read the first
  88. line from the next file (if any); lines not read from the file will
  89. not count towards the cumulative line count. The filename is not
  90. changed until after the first line of the next file has been read.
  91. Before the first line has been read, this function has no effect;
  92. it cannot be used to skip the first file. After the last line of the
  93. last file has been read, this function has no effect.
  94. """
  95. if not _state:
  96. raise RuntimeError, "no active input()"
  97. return _state.nextfile()
  98. def filename():
  99. """
  100. Return the name of the file currently being read.
  101. Before the first line has been read, returns None.
  102. """
  103. if not _state:
  104. raise RuntimeError, "no active input()"
  105. return _state.filename()
  106. def lineno():
  107. """
  108. Return the cumulative line number of the line that has just been read.
  109. Before the first line has been read, returns 0. After the last line
  110. of the last file has been read, returns the line number of that line.
  111. """
  112. if not _state:
  113. raise RuntimeError, "no active input()"
  114. return _state.lineno()
  115. def filelineno():
  116. """
  117. Return the line number in the current file. Before the first line
  118. has been read, returns 0. After the last line of the last file has
  119. been read, returns the line number of that line within the file.
  120. """
  121. if not _state:
  122. raise RuntimeError, "no active input()"
  123. return _state.filelineno()
  124. def fileno():
  125. """
  126. Return the file number of the current file. When no file is currently
  127. opened, returns -1.
  128. """
  129. if not _state:
  130. raise RuntimeError, "no active input()"
  131. return _state.fileno()
  132. def isfirstline():
  133. """
  134. Returns true the line just read is the first line of its file,
  135. otherwise returns false.
  136. """
  137. if not _state:
  138. raise RuntimeError, "no active input()"
  139. return _state.isfirstline()
  140. def isstdin():
  141. """
  142. Returns true if the last line was read from sys.stdin,
  143. otherwise returns false.
  144. """
  145. if not _state:
  146. raise RuntimeError, "no active input()"
  147. return _state.isstdin()
  148. class FileInput:
  149. """FileInput([files[, inplace[, backup[, bufsize[, mode[, openhook]]]]]])
  150. Class FileInput is the implementation of the module; its methods
  151. filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
  152. nextfile() and close() correspond to the functions of the same name
  153. in the module.
  154. In addition it has a readline() method which returns the next
  155. input line, and a __getitem__() method which implements the
  156. sequence behavior. The sequence must be accessed in strictly
  157. sequential order; random access and readline() cannot be mixed.
  158. """
  159. def __init__(self, files=None, inplace=0, backup="", bufsize=0,
  160. mode="r", openhook=None):
  161. if isinstance(files, basestring):
  162. files = (files,)
  163. else:
  164. if files is None:
  165. files = sys.argv[1:]
  166. if not files:
  167. files = ('-',)
  168. else:
  169. files = tuple(files)
  170. self._files = files
  171. self._inplace = inplace
  172. self._backup = backup
  173. self._savestdout = None
  174. self._output = None
  175. self._filename = None
  176. self._startlineno = 0
  177. self._filelineno = 0
  178. self._file = None
  179. self._isstdin = False
  180. self._backupfilename = None
  181. # restrict mode argument to reading modes
  182. if mode not in ('r', 'rU', 'U', 'rb'):
  183. raise ValueError("FileInput opening mode must be one of "
  184. "'r', 'rU', 'U' and 'rb'")
  185. self._mode = mode
  186. if inplace and openhook:
  187. raise ValueError("FileInput cannot use an opening hook in inplace mode")
  188. elif openhook and not hasattr(openhook, '__call__'):
  189. raise ValueError("FileInput openhook must be callable")
  190. self._openhook = openhook
  191. def __del__(self):
  192. self.close()
  193. def close(self):
  194. try:
  195. self.nextfile()
  196. finally:
  197. self._files = ()
  198. def __iter__(self):
  199. return self
  200. def next(self):
  201. while 1:
  202. line = self._readline()
  203. if line:
  204. self._filelineno += 1
  205. return line
  206. if not self._file:
  207. raise StopIteration
  208. self.nextfile()
  209. # repeat with next file
  210. def __getitem__(self, i):
  211. if i != self.lineno():
  212. raise RuntimeError, "accessing lines out of order"
  213. try:
  214. return self.next()
  215. except StopIteration:
  216. raise IndexError, "end of input reached"
  217. def nextfile(self):
  218. savestdout = self._savestdout
  219. self._savestdout = 0
  220. if savestdout:
  221. sys.stdout = savestdout
  222. output = self._output
  223. self._output = 0
  224. try:
  225. if output:
  226. output.close()
  227. finally:
  228. file = self._file
  229. self._file = None
  230. try:
  231. del self._readline # restore FileInput._readline
  232. except AttributeError:
  233. pass
  234. try:
  235. if file and not self._isstdin:
  236. file.close()
  237. finally:
  238. backupfilename = self._backupfilename
  239. self._backupfilename = 0
  240. if backupfilename and not self._backup:
  241. try: os.unlink(backupfilename)
  242. except OSError: pass
  243. self._isstdin = False
  244. def readline(self):
  245. while 1:
  246. line = self._readline()
  247. if line:
  248. self._filelineno += 1
  249. return line
  250. if not self._file:
  251. return line
  252. self.nextfile()
  253. # repeat with next file
  254. def _readline(self):
  255. if not self._files:
  256. return ""
  257. self._filename = self._files[0]
  258. self._files = self._files[1:]
  259. self._startlineno = self.lineno()
  260. self._filelineno = 0
  261. self._file = None
  262. self._isstdin = False
  263. self._backupfilename = 0
  264. if self._filename == '-':
  265. self._filename = '<stdin>'
  266. self._file = sys.stdin
  267. self._isstdin = True
  268. else:
  269. if self._inplace:
  270. self._backupfilename = (
  271. self._filename + (self._backup or os.extsep+"bak"))
  272. try: os.unlink(self._backupfilename)
  273. except os.error: pass
  274. # The next few lines may raise IOError
  275. os.rename(self._filename, self._backupfilename)
  276. self._file = open(self._backupfilename, self._mode)
  277. try:
  278. perm = os.fstat(self._file.fileno()).st_mode
  279. except OSError:
  280. self._output = open(self._filename, "w")
  281. else:
  282. fd = os.open(self._filename,
  283. os.O_CREAT | os.O_WRONLY | os.O_TRUNC,
  284. perm)
  285. self._output = os.fdopen(fd, "w")
  286. try:
  287. if hasattr(os, 'chmod'):
  288. os.chmod(self._filename, perm)
  289. except OSError:
  290. pass
  291. self._savestdout = sys.stdout
  292. sys.stdout = self._output
  293. else:
  294. # This may raise IOError
  295. if self._openhook:
  296. self._file = self._openhook(self._filename, self._mode)
  297. else:
  298. self._file = open(self._filename, self._mode)
  299. self._readline = self._file.readline # hide FileInput._readline
  300. return self._readline()
  301. def filename(self):
  302. return self._filename
  303. def lineno(self):
  304. return self._startlineno + self._filelineno
  305. def filelineno(self):
  306. return self._filelineno
  307. def fileno(self):
  308. if self._file:
  309. try:
  310. return self._file.fileno()
  311. except ValueError:
  312. return -1
  313. else:
  314. return -1
  315. def isfirstline(self):
  316. return self._filelineno == 1
  317. def isstdin(self):
  318. return self._isstdin
  319. def hook_compressed(filename, mode):
  320. ext = os.path.splitext(filename)[1]
  321. if ext == '.gz':
  322. import gzip
  323. return gzip.open(filename, mode)
  324. elif ext == '.bz2':
  325. import bz2
  326. return bz2.BZ2File(filename, mode)
  327. else:
  328. return open(filename, mode)
  329. def hook_encoded(encoding):
  330. import io
  331. def openhook(filename, mode):
  332. mode = mode.replace('U', '').replace('b', '') or 'r'
  333. return io.open(filename, mode, encoding=encoding, newline='')
  334. return openhook
  335. def _test():
  336. import getopt
  337. inplace = 0
  338. backup = 0
  339. opts, args = getopt.getopt(sys.argv[1:], "ib:")
  340. for o, a in opts:
  341. if o == '-i': inplace = 1
  342. if o == '-b': backup = a
  343. for line in input(args, inplace=inplace, backup=backup):
  344. if line[-1:] == '\n': line = line[:-1]
  345. if line[-1:] == '\r': line = line[:-1]
  346. print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
  347. isfirstline() and "*" or "", line)
  348. print "%d: %s[%d]" % (lineno(), filename(), filelineno())
  349. if __name__ == '__main__':
  350. _test()