blob: 004cf09b32429a27c1dde22a9567e408c4e6e3a4 [file] [log] [blame]
Guido van Rossum7d5b99d1997-11-21 17:12:59 +00001"""Helper class to quickly write a loop over all standard input files.
2
3Typical use is:
4
5 import fileinput
6 for line in fileinput.input():
7 process(line)
8
9This iterates over the lines of all files listed in sys.argv[1:],
10defaulting to sys.stdin if the list is empty. If a filename is '-' it
11is also replaced by sys.stdin. To specify an alternative list of
12filenames, pass it as the argument to input(). A single file name is
13also allowed.
14
15Functions filename(), lineno() return the filename and cumulative line
16number of the line that has just been read; filelineno() returns its
17line number in the current file; isfirstline() returns true iff the
18line just read is the first line of its file; isstdin() returns true
19iff the line was read from sys.stdin. Function nextfile() closes the
20current file so that the next iteration will read the first line from
21the next file (if any); lines not read from the file will not count
22towards the cumulative line count; the filename is not changed until
23after the first line of the next file has been read. Function close()
24closes the sequence.
25
26Before any lines have been read, filename() returns None and both line
27numbers are zero; nextfile() has no effect. After all lines have been
28read, filename() and the line number functions return the values
29pertaining to the last line read; nextfile() has no effect.
30
Georg Brandlc029f872006-02-19 14:12:34 +000031All files are opened in text mode by default, you can override this by
32setting the mode parameter to input() or FileInput.__init__().
33If an I/O error occurs during opening or reading a file, the IOError
34exception is raised.
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000035
36If sys.stdin is used more than once, the second and further use will
37return no lines, except perhaps for interactive use, or if it has been
38explicitly reset (e.g. using sys.stdin.seek(0)).
39
40Empty files are opened and immediately closed; the only time their
41presence in the list of filenames is noticeable at all is when the
42last file opened is empty.
43
44It is possible that the last line of a file doesn't end in a newline
45character; otherwise lines are returned including the trailing
46newline.
47
48Class FileInput is the implementation; its methods filename(),
49lineno(), fileline(), isfirstline(), isstdin(), nextfile() and close()
50correspond to the functions in the module. In addition it has a
51readline() method which returns the next input line, and a
52__getitem__() method which implements the sequence behavior. The
53sequence must be accessed in strictly sequential order; sequence
54access and readline() cannot be mixed.
55
56Optional in-place filtering: if the keyword argument inplace=1 is
57passed to input() or to the FileInput constructor, the file is moved
58to a backup file and standard output is directed to the input file.
59This makes it possible to write a filter that rewrites its input file
60in place. If the keyword argument backup=".<some extension>" is also
61given, it specifies the extension for the backup file, and the backup
62file remains around; by default, the extension is ".bak" and it is
63deleted when the output file is closed. In-place filtering is
64disabled when standard input is read. XXX The current implementation
65does not work for MS-DOS 8+3 filesystems.
66
Guido van Rossum47955242001-01-05 14:44:39 +000067Performance: this module is unfortunately one of the slower ways of
68processing large numbers of input lines. Nevertheless, a significant
69speed-up has been obtained by using readlines(bufsize) instead of
70readline(). A new keyword argument, bufsize=N, is present on the
71input() function and the FileInput() class to override the default
72buffer size.
73
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000074XXX Possible additions:
75
76- optional getopt argument processing
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000077- isatty()
78- read(), read(size), even readlines()
79
80"""
81
Walter Dörwald294bbf32002-06-06 09:48:13 +000082import sys, os
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000083
Skip Montanaroeccd02a2001-01-20 23:34:12 +000084__all__ = ["input","close","nextfile","filename","lineno","filelineno",
85 "isfirstline","isstdin","FileInput"]
86
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000087_state = None
88
Guido van Rossum47955242001-01-05 14:44:39 +000089DEFAULT_BUFSIZE = 8*1024
90
Georg Brandlc029f872006-02-19 14:12:34 +000091def input(files=None, inplace=0, backup="", bufsize=0, mode="r"):
92 """input([files[, inplace[, backup[, mode]]]])
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +000093
94 Create an instance of the FileInput class. The instance will be used
95 as global state for the functions of this module, and is also returned
96 to use during iteration. The parameters to this function will be passed
Tim Peters8ac14952002-05-23 15:15:30 +000097 along to the constructor of the FileInput class.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +000098 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000099 global _state
100 if _state and _state._file:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000101 raise RuntimeError, "input() already active"
Georg Brandlc029f872006-02-19 14:12:34 +0000102 _state = FileInput(files, inplace, backup, bufsize, mode)
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000103 return _state
104
105def close():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000106 """Close the sequence."""
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000107 global _state
108 state = _state
109 _state = None
110 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 state.close()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000112
113def nextfile():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000114 """
115 Close the current file so that the next iteration will read the first
116 line from the next file (if any); lines not read from the file will
117 not count towards the cumulative line count. The filename is not
118 changed until after the first line of the next file has been read.
119 Before the first line has been read, this function has no effect;
120 it cannot be used to skip the first file. After the last line of the
Tim Peters8ac14952002-05-23 15:15:30 +0000121 last file has been read, this function has no effect.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000122 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000123 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000124 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000125 return _state.nextfile()
126
127def filename():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000128 """
129 Return the name of the file currently being read.
Tim Peters8ac14952002-05-23 15:15:30 +0000130 Before the first line has been read, returns None.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000131 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000132 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000133 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000134 return _state.filename()
135
136def lineno():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000137 """
138 Return the cumulative line number of the line that has just been read.
139 Before the first line has been read, returns 0. After the last line
Tim Peters8ac14952002-05-23 15:15:30 +0000140 of the last file has been read, returns the line number of that line.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000141 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000142 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000143 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000144 return _state.lineno()
145
146def filelineno():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000147 """
148 Return the line number in the current file. Before the first line
149 has been read, returns 0. After the last line of the last file has
Tim Peters8ac14952002-05-23 15:15:30 +0000150 been read, returns the line number of that line within the file.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000151 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000152 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000153 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000154 return _state.filelineno()
155
Georg Brandl67e9fb92006-02-19 13:56:17 +0000156def fileno():
157 """
158 Return the file number of the current file. When no file is currently
159 opened, returns -1.
160 """
161 if not _state:
162 raise RuntimeError, "no active input()"
163 return _state.fileno()
164
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000165def isfirstline():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000166 """
167 Returns true the line just read is the first line of its file,
Tim Peters8ac14952002-05-23 15:15:30 +0000168 otherwise returns false.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000169 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000170 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000171 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000172 return _state.isfirstline()
173
174def isstdin():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000175 """
176 Returns true if the last line was read from sys.stdin,
Tim Peters8ac14952002-05-23 15:15:30 +0000177 otherwise returns false.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000178 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000179 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000180 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000181 return _state.isstdin()
182
183class FileInput:
Georg Brandlc029f872006-02-19 14:12:34 +0000184 """class FileInput([files[, inplace[, backup[, mode]]]])
Tim Peters8ac14952002-05-23 15:15:30 +0000185
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000186 Class FileInput is the implementation of the module; its methods
Georg Brandl67e9fb92006-02-19 13:56:17 +0000187 filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
188 nextfile() and close() correspond to the functions of the same name
189 in the module.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000190 In addition it has a readline() method which returns the next
191 input line, and a __getitem__() method which implements the
192 sequence behavior. The sequence must be accessed in strictly
Tim Peters8ac14952002-05-23 15:15:30 +0000193 sequential order; random access and readline() cannot be mixed.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000194 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000195
Georg Brandlc029f872006-02-19 14:12:34 +0000196 def __init__(self, files=None, inplace=0, backup="", bufsize=0, mode="r"):
Georg Brandle4662172006-02-19 09:51:27 +0000197 if isinstance(files, basestring):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000198 files = (files,)
199 else:
Guido van Rossum2516b392000-04-10 17:16:12 +0000200 if files is None:
201 files = sys.argv[1:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000202 if not files:
Guido van Rossum2516b392000-04-10 17:16:12 +0000203 files = ('-',)
204 else:
205 files = tuple(files)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000206 self._files = files
207 self._inplace = inplace
208 self._backup = backup
Guido van Rossum47955242001-01-05 14:44:39 +0000209 self._bufsize = bufsize or DEFAULT_BUFSIZE
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000210 self._savestdout = None
211 self._output = None
212 self._filename = None
213 self._lineno = 0
214 self._filelineno = 0
215 self._file = None
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000216 self._isstdin = False
Guido van Rossum0aec9fb1998-07-20 15:49:28 +0000217 self._backupfilename = None
Guido van Rossum47955242001-01-05 14:44:39 +0000218 self._buffer = []
219 self._bufindex = 0
Georg Brandlc029f872006-02-19 14:12:34 +0000220 # restrict mode argument to reading modes
221 if mode not in ('r', 'rU', 'U', 'rb'):
222 raise ValueError("FileInput opening mode must be one of "
223 "'r', 'rU', 'U' and 'rb'")
224 self._mode = mode
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000225
226 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000227 self.close()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000228
229 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000230 self.nextfile()
231 self._files = ()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000232
Neil Schemenauer908632a2002-03-26 20:28:40 +0000233 def __iter__(self):
234 return self
235
236 def next(self):
Guido van Rossum47955242001-01-05 14:44:39 +0000237 try:
238 line = self._buffer[self._bufindex]
239 except IndexError:
240 pass
241 else:
242 self._bufindex += 1
243 self._lineno += 1
244 self._filelineno += 1
245 return line
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 line = self.readline()
247 if not line:
Neil Schemenauer908632a2002-03-26 20:28:40 +0000248 raise StopIteration
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000249 return line
Tim Peters863ac442002-04-16 01:38:40 +0000250
Neil Schemenauer908632a2002-03-26 20:28:40 +0000251 def __getitem__(self, i):
252 if i != self._lineno:
253 raise RuntimeError, "accessing lines out of order"
254 try:
255 return self.next()
256 except StopIteration:
257 raise IndexError, "end of input reached"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000258
259 def nextfile(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 savestdout = self._savestdout
261 self._savestdout = 0
262 if savestdout:
263 sys.stdout = savestdout
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000264
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000265 output = self._output
266 self._output = 0
267 if output:
268 output.close()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000269
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000270 file = self._file
271 self._file = 0
272 if file and not self._isstdin:
273 file.close()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000274
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000275 backupfilename = self._backupfilename
276 self._backupfilename = 0
277 if backupfilename and not self._backup:
278 try: os.unlink(backupfilename)
Skip Montanarocffac662002-08-14 02:58:16 +0000279 except OSError: pass
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000280
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000281 self._isstdin = False
Guido van Rossum47955242001-01-05 14:44:39 +0000282 self._buffer = []
283 self._bufindex = 0
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000284
285 def readline(self):
Guido van Rossum47955242001-01-05 14:44:39 +0000286 try:
287 line = self._buffer[self._bufindex]
288 except IndexError:
289 pass
290 else:
291 self._bufindex += 1
292 self._lineno += 1
293 self._filelineno += 1
294 return line
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000295 if not self._file:
296 if not self._files:
297 return ""
298 self._filename = self._files[0]
299 self._files = self._files[1:]
300 self._filelineno = 0
301 self._file = None
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000302 self._isstdin = False
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000303 self._backupfilename = 0
304 if self._filename == '-':
305 self._filename = '<stdin>'
306 self._file = sys.stdin
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000307 self._isstdin = True
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000308 else:
309 if self._inplace:
310 self._backupfilename = (
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000311 self._filename + (self._backup or os.extsep+"bak"))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000312 try: os.unlink(self._backupfilename)
313 except os.error: pass
Guido van Rossumdcb85831999-10-18 21:41:43 +0000314 # The next few lines may raise IOError
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000315 os.rename(self._filename, self._backupfilename)
Georg Brandlc029f872006-02-19 14:12:34 +0000316 self._file = open(self._backupfilename, self._mode)
Guido van Rossumdcb85831999-10-18 21:41:43 +0000317 try:
Walter Dörwald294bbf32002-06-06 09:48:13 +0000318 perm = os.fstat(self._file.fileno()).st_mode
Skip Montanarocffac662002-08-14 02:58:16 +0000319 except OSError:
Guido van Rossumdcb85831999-10-18 21:41:43 +0000320 self._output = open(self._filename, "w")
321 else:
322 fd = os.open(self._filename,
323 os.O_CREAT | os.O_WRONLY | os.O_TRUNC,
324 perm)
325 self._output = os.fdopen(fd, "w")
326 try:
Jack Jansen52941a82003-01-08 16:33:16 +0000327 if hasattr(os, 'chmod'):
328 os.chmod(self._filename, perm)
Skip Montanarocffac662002-08-14 02:58:16 +0000329 except OSError:
Guido van Rossumdcb85831999-10-18 21:41:43 +0000330 pass
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000331 self._savestdout = sys.stdout
332 sys.stdout = self._output
333 else:
334 # This may raise IOError
Georg Brandlc029f872006-02-19 14:12:34 +0000335 self._file = open(self._filename, self._mode)
Guido van Rossum47955242001-01-05 14:44:39 +0000336 self._buffer = self._file.readlines(self._bufsize)
337 self._bufindex = 0
338 if not self._buffer:
339 self.nextfile()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000340 # Recursive call
341 return self.readline()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000342
343 def filename(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000344 return self._filename
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000345
346 def lineno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000347 return self._lineno
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000348
349 def filelineno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000350 return self._filelineno
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000351
Georg Brandl67e9fb92006-02-19 13:56:17 +0000352 def fileno(self):
353 if self._file:
354 try:
355 return self._file.fileno()
356 except ValueError:
357 return -1
358 else:
359 return -1
360
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000361 def isfirstline(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000362 return self._filelineno == 1
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000363
364 def isstdin(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000365 return self._isstdin
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000366
367def _test():
368 import getopt
369 inplace = 0
370 backup = 0
371 opts, args = getopt.getopt(sys.argv[1:], "ib:")
372 for o, a in opts:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000373 if o == '-i': inplace = 1
374 if o == '-b': backup = a
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000375 for line in input(args, inplace=inplace, backup=backup):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000376 if line[-1:] == '\n': line = line[:-1]
377 if line[-1:] == '\r': line = line[:-1]
378 print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
379 isfirstline() and "*" or "", line)
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000380 print "%d: %s[%d]" % (lineno(), filename(), filelineno())
381
382if __name__ == '__main__':
383 _test()