fileinput.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 and the optional arguments mode and
  9. openhook are ignored. To specify an alternative list of filenames,
  10. pass it as the argument to input(). A single file name is 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 OSError
  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. "fileno", "isfirstline", "isstdin", "FileInput", "hook_compressed",
  63. "hook_encoded"]
  64. _state = None
  65. def input(files=None, inplace=False, backup="", *, mode="r", openhook=None):
  66. """Return an instance of the FileInput class, which can be iterated.
  67. The parameters are passed to the constructor of the FileInput class.
  68. The returned instance, in addition to being an iterator,
  69. keeps global state for the functions of this module,.
  70. """
  71. global _state
  72. if _state and _state._file:
  73. raise RuntimeError("input() already active")
  74. _state = FileInput(files, inplace, backup, mode=mode, openhook=openhook)
  75. return _state
  76. def close():
  77. """Close the sequence."""
  78. global _state
  79. state = _state
  80. _state = None
  81. if state:
  82. state.close()
  83. def nextfile():
  84. """
  85. Close the current file so that the next iteration will read the first
  86. line from the next file (if any); lines not read from the file will
  87. not count towards the cumulative line count. The filename is not
  88. changed until after the first line of the next file has been read.
  89. Before the first line has been read, this function has no effect;
  90. it cannot be used to skip the first file. After the last line of the
  91. last file has been read, this function has no effect.
  92. """
  93. if not _state:
  94. raise RuntimeError("no active input()")
  95. return _state.nextfile()
  96. def filename():
  97. """
  98. Return the name of the file currently being read.
  99. Before the first line has been read, returns None.
  100. """
  101. if not _state:
  102. raise RuntimeError("no active input()")
  103. return _state.filename()
  104. def lineno():
  105. """
  106. Return the cumulative line number of the line that has just been read.
  107. Before the first line has been read, returns 0. After the last line
  108. of the last file has been read, returns the line number of that line.
  109. """
  110. if not _state:
  111. raise RuntimeError("no active input()")
  112. return _state.lineno()
  113. def filelineno():
  114. """
  115. Return the line number in the current file. Before the first line
  116. has been read, returns 0. After the last line of the last file has
  117. been read, returns the line number of that line within the file.
  118. """
  119. if not _state:
  120. raise RuntimeError("no active input()")
  121. return _state.filelineno()
  122. def fileno():
  123. """
  124. Return the file number of the current file. When no file is currently
  125. opened, returns -1.
  126. """
  127. if not _state:
  128. raise RuntimeError("no active input()")
  129. return _state.fileno()
  130. def isfirstline():
  131. """
  132. Returns true the line just read is the first line of its file,
  133. otherwise returns false.
  134. """
  135. if not _state:
  136. raise RuntimeError("no active input()")
  137. return _state.isfirstline()
  138. def isstdin():
  139. """
  140. Returns true if the last line was read from sys.stdin,
  141. otherwise returns false.
  142. """
  143. if not _state:
  144. raise RuntimeError("no active input()")
  145. return _state.isstdin()
  146. class FileInput:
  147. """FileInput([files[, inplace[, backup]]], *, mode=None, openhook=None)
  148. Class FileInput is the implementation of the module; its methods
  149. filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
  150. nextfile() and close() correspond to the functions of the same name
  151. in the module.
  152. In addition it has a readline() method which returns the next
  153. input line, and a __getitem__() method which implements the
  154. sequence behavior. The sequence must be accessed in strictly
  155. sequential order; random access and readline() cannot be mixed.
  156. """
  157. def __init__(self, files=None, inplace=False, backup="", *,
  158. mode="r", openhook=None):
  159. if isinstance(files, str):
  160. files = (files,)
  161. elif isinstance(files, os.PathLike):
  162. files = (os.fspath(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. if 'U' in mode:
  186. import warnings
  187. warnings.warn("'U' mode is deprecated",
  188. DeprecationWarning, 2)
  189. self._mode = mode
  190. self._write_mode = mode.replace('r', 'w') if 'U' not in mode else 'w'
  191. if openhook:
  192. if inplace:
  193. raise ValueError("FileInput cannot use an opening hook in inplace mode")
  194. if not callable(openhook):
  195. raise ValueError("FileInput openhook must be callable")
  196. self._openhook = openhook
  197. def __del__(self):
  198. self.close()
  199. def close(self):
  200. try:
  201. self.nextfile()
  202. finally:
  203. self._files = ()
  204. def __enter__(self):
  205. return self
  206. def __exit__(self, type, value, traceback):
  207. self.close()
  208. def __iter__(self):
  209. return self
  210. def __next__(self):
  211. while True:
  212. line = self._readline()
  213. if line:
  214. self._filelineno += 1
  215. return line
  216. if not self._file:
  217. raise StopIteration
  218. self.nextfile()
  219. # repeat with next file
  220. def __getitem__(self, i):
  221. import warnings
  222. warnings.warn(
  223. "Support for indexing FileInput objects is deprecated. "
  224. "Use iterator protocol instead.",
  225. DeprecationWarning,
  226. stacklevel=2
  227. )
  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 = None
  237. if savestdout:
  238. sys.stdout = savestdout
  239. output = self._output
  240. self._output = None
  241. try:
  242. if output:
  243. output.close()
  244. finally:
  245. file = self._file
  246. self._file = None
  247. try:
  248. del self._readline # restore FileInput._readline
  249. except AttributeError:
  250. pass
  251. try:
  252. if file and not self._isstdin:
  253. file.close()
  254. finally:
  255. backupfilename = self._backupfilename
  256. self._backupfilename = None
  257. if backupfilename and not self._backup:
  258. try: os.unlink(backupfilename)
  259. except OSError: pass
  260. self._isstdin = False
  261. def readline(self):
  262. while True:
  263. line = self._readline()
  264. if line:
  265. self._filelineno += 1
  266. return line
  267. if not self._file:
  268. return line
  269. self.nextfile()
  270. # repeat with next file
  271. def _readline(self):
  272. if not self._files:
  273. if 'b' in self._mode:
  274. return b''
  275. else:
  276. return ''
  277. self._filename = self._files[0]
  278. self._files = self._files[1:]
  279. self._startlineno = self.lineno()
  280. self._filelineno = 0
  281. self._file = None
  282. self._isstdin = False
  283. self._backupfilename = 0
  284. if self._filename == '-':
  285. self._filename = '<stdin>'
  286. if 'b' in self._mode:
  287. self._file = getattr(sys.stdin, 'buffer', sys.stdin)
  288. else:
  289. self._file = sys.stdin
  290. self._isstdin = True
  291. else:
  292. if self._inplace:
  293. self._backupfilename = (
  294. os.fspath(self._filename) + (self._backup or ".bak"))
  295. try:
  296. os.unlink(self._backupfilename)
  297. except OSError:
  298. pass
  299. # The next few lines may raise OSError
  300. os.rename(self._filename, self._backupfilename)
  301. self._file = open(self._backupfilename, self._mode)
  302. try:
  303. perm = os.fstat(self._file.fileno()).st_mode
  304. except OSError:
  305. self._output = open(self._filename, self._write_mode)
  306. else:
  307. mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
  308. if hasattr(os, 'O_BINARY'):
  309. mode |= os.O_BINARY
  310. fd = os.open(self._filename, mode, perm)
  311. self._output = os.fdopen(fd, self._write_mode)
  312. try:
  313. os.chmod(self._filename, perm)
  314. except OSError:
  315. pass
  316. self._savestdout = sys.stdout
  317. sys.stdout = self._output
  318. else:
  319. # This may raise OSError
  320. if self._openhook:
  321. self._file = self._openhook(self._filename, self._mode)
  322. else:
  323. self._file = open(self._filename, self._mode)
  324. self._readline = self._file.readline # hide FileInput._readline
  325. return self._readline()
  326. def filename(self):
  327. return self._filename
  328. def lineno(self):
  329. return self._startlineno + self._filelineno
  330. def filelineno(self):
  331. return self._filelineno
  332. def fileno(self):
  333. if self._file:
  334. try:
  335. return self._file.fileno()
  336. except ValueError:
  337. return -1
  338. else:
  339. return -1
  340. def isfirstline(self):
  341. return self._filelineno == 1
  342. def isstdin(self):
  343. return self._isstdin
  344. def hook_compressed(filename, mode):
  345. ext = os.path.splitext(filename)[1]
  346. if ext == '.gz':
  347. import gzip
  348. return gzip.open(filename, mode)
  349. elif ext == '.bz2':
  350. import bz2
  351. return bz2.BZ2File(filename, mode)
  352. else:
  353. return open(filename, mode)
  354. def hook_encoded(encoding, errors=None):
  355. def openhook(filename, mode):
  356. return open(filename, mode, encoding=encoding, errors=errors)
  357. return openhook
  358. def _test():
  359. import getopt
  360. inplace = False
  361. backup = False
  362. opts, args = getopt.getopt(sys.argv[1:], "ib:")
  363. for o, a in opts:
  364. if o == '-i': inplace = True
  365. if o == '-b': backup = a
  366. for line in input(args, inplace=inplace, backup=backup):
  367. if line[-1:] == '\n': line = line[:-1]
  368. if line[-1:] == '\r': line = line[:-1]
  369. print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
  370. isfirstline() and "*" or "", line))
  371. print("%d: %s[%d]" % (lineno(), filename(), filelineno()))
  372. if __name__ == '__main__':
  373. _test()