You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

422 lines
14 KiB

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