PageRenderTime 50ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/fileinput.py

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