fileinput.py 14 KB

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