fileinput.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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="", bufsize=0,
  66. 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, bufsize, mode, 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[, bufsize, [, mode[, openhook]]]]]])
  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="", bufsize=0,
  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. if bufsize:
  175. import warnings
  176. warnings.warn('bufsize is deprecated and ignored',
  177. DeprecationWarning, stacklevel=2)
  178. self._savestdout = None
  179. self._output = None
  180. self._filename = None
  181. self._startlineno = 0
  182. self._filelineno = 0
  183. self._file = None
  184. self._isstdin = False
  185. self._backupfilename = None
  186. # restrict mode argument to reading modes
  187. if mode not in ('r', 'rU', 'U', 'rb'):
  188. raise ValueError("FileInput opening mode must be one of "
  189. "'r', 'rU', 'U' and 'rb'")
  190. if 'U' in mode:
  191. import warnings
  192. warnings.warn("'U' mode is deprecated",
  193. DeprecationWarning, 2)
  194. self._mode = mode
  195. if openhook:
  196. if inplace:
  197. raise ValueError("FileInput cannot use an opening hook in inplace mode")
  198. if not callable(openhook):
  199. raise ValueError("FileInput openhook must be callable")
  200. self._openhook = openhook
  201. def __del__(self):
  202. self.close()
  203. def close(self):
  204. try:
  205. self.nextfile()
  206. finally:
  207. self._files = ()
  208. def __enter__(self):
  209. return self
  210. def __exit__(self, type, value, traceback):
  211. self.close()
  212. def __iter__(self):
  213. return self
  214. def __next__(self):
  215. while True:
  216. line = self._readline()
  217. if line:
  218. self._filelineno += 1
  219. return line
  220. if not self._file:
  221. raise StopIteration
  222. self.nextfile()
  223. # repeat with next file
  224. def __getitem__(self, i):
  225. if i != self.lineno():
  226. raise RuntimeError("accessing lines out of order")
  227. try:
  228. return self.__next__()
  229. except StopIteration:
  230. raise IndexError("end of input reached")
  231. def nextfile(self):
  232. savestdout = self._savestdout
  233. self._savestdout = None
  234. if savestdout:
  235. sys.stdout = savestdout
  236. output = self._output
  237. self._output = None
  238. try:
  239. if output:
  240. output.close()
  241. finally:
  242. file = self._file
  243. self._file = None
  244. try:
  245. del self._readline # restore FileInput._readline
  246. except AttributeError:
  247. pass
  248. try:
  249. if file and not self._isstdin:
  250. file.close()
  251. finally:
  252. backupfilename = self._backupfilename
  253. self._backupfilename = None
  254. if backupfilename and not self._backup:
  255. try: os.unlink(backupfilename)
  256. except OSError: pass
  257. self._isstdin = False
  258. def readline(self):
  259. while True:
  260. line = self._readline()
  261. if line:
  262. self._filelineno += 1
  263. return line
  264. if not self._file:
  265. return line
  266. self.nextfile()
  267. # repeat with next file
  268. def _readline(self):
  269. if not self._files:
  270. if 'b' in self._mode:
  271. return b''
  272. else:
  273. return ''
  274. self._filename = self._files[0]
  275. self._files = self._files[1:]
  276. self._startlineno = self.lineno()
  277. self._filelineno = 0
  278. self._file = None
  279. self._isstdin = False
  280. self._backupfilename = 0
  281. if self._filename == '-':
  282. self._filename = '<stdin>'
  283. if 'b' in self._mode:
  284. self._file = getattr(sys.stdin, 'buffer', sys.stdin)
  285. else:
  286. self._file = sys.stdin
  287. self._isstdin = True
  288. else:
  289. if self._inplace:
  290. self._backupfilename = (
  291. os.fspath(self._filename) + (self._backup or ".bak"))
  292. try:
  293. os.unlink(self._backupfilename)
  294. except OSError:
  295. pass
  296. # The next few lines may raise OSError
  297. os.rename(self._filename, self._backupfilename)
  298. self._file = open(self._backupfilename, self._mode)
  299. try:
  300. perm = os.fstat(self._file.fileno()).st_mode
  301. except OSError:
  302. self._output = open(self._filename, "w")
  303. else:
  304. mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
  305. if hasattr(os, 'O_BINARY'):
  306. mode |= os.O_BINARY
  307. fd = os.open(self._filename, mode, perm)
  308. self._output = os.fdopen(fd, "w")
  309. try:
  310. if hasattr(os, 'chmod'):
  311. os.chmod(self._filename, perm)
  312. except OSError:
  313. pass
  314. self._savestdout = sys.stdout
  315. sys.stdout = self._output
  316. else:
  317. # This may raise OSError
  318. if self._openhook:
  319. self._file = self._openhook(self._filename, self._mode)
  320. else:
  321. self._file = open(self._filename, self._mode)
  322. self._readline = self._file.readline # hide FileInput._readline
  323. return self._readline()
  324. def filename(self):
  325. return self._filename
  326. def lineno(self):
  327. return self._startlineno + self._filelineno
  328. def filelineno(self):
  329. return self._filelineno
  330. def fileno(self):
  331. if self._file:
  332. try:
  333. return self._file.fileno()
  334. except ValueError:
  335. return -1
  336. else:
  337. return -1
  338. def isfirstline(self):
  339. return self._filelineno == 1
  340. def isstdin(self):
  341. return self._isstdin
  342. def hook_compressed(filename, mode):
  343. ext = os.path.splitext(filename)[1]
  344. if ext == '.gz':
  345. import gzip
  346. return gzip.open(filename, mode)
  347. elif ext == '.bz2':
  348. import bz2
  349. return bz2.BZ2File(filename, mode)
  350. else:
  351. return open(filename, mode)
  352. def hook_encoded(encoding, errors=None):
  353. def openhook(filename, mode):
  354. return open(filename, mode, encoding=encoding, errors=errors)
  355. return openhook
  356. def _test():
  357. import getopt
  358. inplace = False
  359. backup = False
  360. opts, args = getopt.getopt(sys.argv[1:], "ib:")
  361. for o, a in opts:
  362. if o == '-i': inplace = True
  363. if o == '-b': backup = a
  364. for line in input(args, inplace=inplace, backup=backup):
  365. if line[-1:] == '\n': line = line[:-1]
  366. if line[-1:] == '\r': line = line[:-1]
  367. print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
  368. isfirstline() and "*" or "", line))
  369. print("%d: %s[%d]" % (lineno(), filename(), filelineno()))
  370. if __name__ == '__main__':
  371. _test()