PageRenderTime 50ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/org.python.pydev.jython/Lib/fileinput.py

https://github.com/MrGreen123/Pydev
Python | 300 lines | 281 code | 6 blank | 13 comment | 12 complexity | b069a6b3d086bf081034d2321c319cd0 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. If an I/O error occurs during
  26. opening or reading a file, the IOError exception is raised.
  27. If sys.stdin is used more than once, the second and further use will
  28. return no lines, except perhaps for interactive use, or if it has been
  29. explicitly reset (e.g. using sys.stdin.seek(0)).
  30. Empty files are opened and immediately closed; the only time their
  31. presence in the list of filenames is noticeable at all is when the
  32. last file opened is empty.
  33. It is possible that the last line of a file doesn't end in a newline
  34. character; otherwise lines are returned including the trailing
  35. newline.
  36. Class FileInput is the implementation; its methods filename(),
  37. lineno(), fileline(), isfirstline(), isstdin(), nextfile() and close()
  38. correspond to the functions in the module. In addition it has a
  39. readline() method which returns the next input line, and a
  40. __getitem__() method which implements the sequence behavior. The
  41. sequence must be accessed in strictly sequential order; sequence
  42. access and readline() cannot be mixed.
  43. Optional in-place filtering: if the keyword argument inplace=1 is
  44. passed to input() or to the FileInput constructor, the file is moved
  45. to a backup file and standard output is directed to the input file.
  46. This makes it possible to write a filter that rewrites its input file
  47. in place. If the keyword argument backup=".<some extension>" is also
  48. given, it specifies the extension for the backup file, and the backup
  49. file remains around; by default, the extension is ".bak" and it is
  50. deleted when the output file is closed. In-place filtering is
  51. disabled when standard input is read. XXX The current implementation
  52. does not work for MS-DOS 8+3 filesystems.
  53. Performance: this module is unfortunately one of the slower ways of
  54. processing large numbers of input lines. Nevertheless, a significant
  55. speed-up has been obtained by using readlines(bufsize) instead of
  56. readline(). A new keyword argument, bufsize=N, is present on the
  57. input() function and the FileInput() class to override the default
  58. buffer size.
  59. XXX Possible additions:
  60. - optional getopt argument processing
  61. - specify open mode ('r' or 'rb')
  62. - fileno()
  63. - isatty()
  64. - read(), read(size), even readlines()
  65. """
  66. import sys, os, stat
  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. global _state
  73. if _state and _state._file:
  74. raise RuntimeError, "input() already active"
  75. _state = FileInput(files, inplace, backup, bufsize)
  76. return _state
  77. def close():
  78. global _state
  79. state = _state
  80. _state = None
  81. if state:
  82. state.close()
  83. def nextfile():
  84. if not _state:
  85. raise RuntimeError, "no active input()"
  86. return _state.nextfile()
  87. def filename():
  88. if not _state:
  89. raise RuntimeError, "no active input()"
  90. return _state.filename()
  91. def lineno():
  92. if not _state:
  93. raise RuntimeError, "no active input()"
  94. return _state.lineno()
  95. def filelineno():
  96. if not _state:
  97. raise RuntimeError, "no active input()"
  98. return _state.filelineno()
  99. def isfirstline():
  100. if not _state:
  101. raise RuntimeError, "no active input()"
  102. return _state.isfirstline()
  103. def isstdin():
  104. if not _state:
  105. raise RuntimeError, "no active input()"
  106. return _state.isstdin()
  107. class FileInput:
  108. def __init__(self, files=None, inplace=0, backup="", bufsize=0):
  109. if type(files) == type(''):
  110. files = (files,)
  111. else:
  112. if files is None:
  113. files = sys.argv[1:]
  114. if not files:
  115. files = ('-',)
  116. else:
  117. files = tuple(files)
  118. self._files = files
  119. self._inplace = inplace
  120. self._backup = backup
  121. self._bufsize = bufsize or DEFAULT_BUFSIZE
  122. self._savestdout = None
  123. self._output = None
  124. self._filename = None
  125. self._lineno = 0
  126. self._filelineno = 0
  127. self._file = None
  128. self._isstdin = 0
  129. self._backupfilename = None
  130. self._buffer = []
  131. self._bufindex = 0
  132. def __del__(self):
  133. self.close()
  134. def close(self):
  135. self.nextfile()
  136. self._files = ()
  137. def __getitem__(self, i):
  138. try:
  139. line = self._buffer[self._bufindex]
  140. except IndexError:
  141. pass
  142. else:
  143. self._bufindex += 1
  144. self._lineno += 1
  145. self._filelineno += 1
  146. return line
  147. if i != self._lineno:
  148. raise RuntimeError, "accessing lines out of order"
  149. line = self.readline()
  150. if not line:
  151. raise IndexError, "end of input reached"
  152. return line
  153. def nextfile(self):
  154. savestdout = self._savestdout
  155. self._savestdout = 0
  156. if savestdout:
  157. sys.stdout = savestdout
  158. output = self._output
  159. self._output = 0
  160. if output:
  161. output.close()
  162. file = self._file
  163. self._file = 0
  164. if file and not self._isstdin:
  165. file.close()
  166. backupfilename = self._backupfilename
  167. self._backupfilename = 0
  168. if backupfilename and not self._backup:
  169. try: os.unlink(backupfilename)
  170. except: pass
  171. self._isstdin = 0
  172. self._buffer = []
  173. self._bufindex = 0
  174. def readline(self):
  175. try:
  176. line = self._buffer[self._bufindex]
  177. except IndexError:
  178. pass
  179. else:
  180. self._bufindex += 1
  181. self._lineno += 1
  182. self._filelineno += 1
  183. return line
  184. if not self._file:
  185. if not self._files:
  186. return ""
  187. self._filename = self._files[0]
  188. self._files = self._files[1:]
  189. self._filelineno = 0
  190. self._file = None
  191. self._isstdin = 0
  192. self._backupfilename = 0
  193. if self._filename == '-':
  194. self._filename = '<stdin>'
  195. self._file = sys.stdin
  196. self._isstdin = 1
  197. else:
  198. if self._inplace:
  199. self._backupfilename = (
  200. self._filename + (self._backup or ".bak"))
  201. try: os.unlink(self._backupfilename)
  202. except os.error: pass
  203. # The next few lines may raise IOError
  204. os.rename(self._filename, self._backupfilename)
  205. self._file = open(self._backupfilename, "r")
  206. try:
  207. perm = os.fstat(self._file.fileno())[stat.ST_MODE]
  208. except:
  209. self._output = open(self._filename, "w")
  210. else:
  211. fd = os.open(self._filename,
  212. os.O_CREAT | os.O_WRONLY | os.O_TRUNC,
  213. perm)
  214. self._output = os.fdopen(fd, "w")
  215. try:
  216. os.chmod(self._filename, perm)
  217. except:
  218. pass
  219. self._savestdout = sys.stdout
  220. sys.stdout = self._output
  221. else:
  222. # This may raise IOError
  223. self._file = open(self._filename, "r")
  224. self._buffer = self._file.readlines(self._bufsize)
  225. self._bufindex = 0
  226. if not self._buffer:
  227. self.nextfile()
  228. # Recursive call
  229. return self.readline()
  230. def filename(self):
  231. return self._filename
  232. def lineno(self):
  233. return self._lineno
  234. def filelineno(self):
  235. return self._filelineno
  236. def isfirstline(self):
  237. return self._filelineno == 1
  238. def isstdin(self):
  239. return self._isstdin
  240. def _test():
  241. import getopt
  242. inplace = 0
  243. backup = 0
  244. opts, args = getopt.getopt(sys.argv[1:], "ib:")
  245. for o, a in opts:
  246. if o == '-i': inplace = 1
  247. if o == '-b': backup = a
  248. for line in input(args, inplace=inplace, backup=backup):
  249. if line[-1:] == '\n': line = line[:-1]
  250. if line[-1:] == '\r': line = line[:-1]
  251. print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
  252. isfirstline() and "*" or "", line)
  253. print "%d: %s[%d]" % (lineno(), filename(), filelineno())
  254. if __name__ == '__main__':
  255. _test()