blob: 692eeea0c79d84d00bb63ed34ba23d18e03c33da [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
31All files are opened in text mode. If an I/O error occurs during
32opening or reading a file, the IOError exception is raised.
33
34If sys.stdin is used more than once, the second and further use will
35return no lines, except perhaps for interactive use, or if it has been
36explicitly reset (e.g. using sys.stdin.seek(0)).
37
38Empty files are opened and immediately closed; the only time their
39presence in the list of filenames is noticeable at all is when the
40last file opened is empty.
41
42It is possible that the last line of a file doesn't end in a newline
43character; otherwise lines are returned including the trailing
44newline.
45
46Class FileInput is the implementation; its methods filename(),
47lineno(), fileline(), isfirstline(), isstdin(), nextfile() and close()
48correspond to the functions in the module. In addition it has a
49readline() method which returns the next input line, and a
50__getitem__() method which implements the sequence behavior. The
51sequence must be accessed in strictly sequential order; sequence
52access and readline() cannot be mixed.
53
54Optional in-place filtering: if the keyword argument inplace=1 is
55passed to input() or to the FileInput constructor, the file is moved
56to a backup file and standard output is directed to the input file.
57This makes it possible to write a filter that rewrites its input file
58in place. If the keyword argument backup=".<some extension>" is also
59given, it specifies the extension for the backup file, and the backup
60file remains around; by default, the extension is ".bak" and it is
61deleted when the output file is closed. In-place filtering is
62disabled when standard input is read. XXX The current implementation
63does not work for MS-DOS 8+3 filesystems.
64
Guido van Rossum47955242001-01-05 14:44:39 +000065Performance: this module is unfortunately one of the slower ways of
66processing large numbers of input lines. Nevertheless, a significant
67speed-up has been obtained by using readlines(bufsize) instead of
68readline(). A new keyword argument, bufsize=N, is present on the
69input() function and the FileInput() class to override the default
70buffer size.
71
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000072XXX Possible additions:
73
74- optional getopt argument processing
75- specify open mode ('r' or 'rb')
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000076- isatty()
77- read(), read(size), even readlines()
78
79"""
80
Walter Dörwald294bbf32002-06-06 09:48:13 +000081import sys, os
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000082
Skip Montanaroeccd02a2001-01-20 23:34:12 +000083__all__ = ["input","close","nextfile","filename","lineno","filelineno",
84 "isfirstline","isstdin","FileInput"]
85
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000086_state = None
87
Guido van Rossum47955242001-01-05 14:44:39 +000088DEFAULT_BUFSIZE = 8*1024
89
90def input(files=None, inplace=0, backup="", bufsize=0):
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +000091 """input([files[, inplace[, backup]]])
92
93 Create an instance of the FileInput class. The instance will be used
94 as global state for the functions of this module, and is also returned
95 to use during iteration. The parameters to this function will be passed
Tim Peters8ac14952002-05-23 15:15:30 +000096 along to the constructor of the FileInput class.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +000097 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000098 global _state
99 if _state and _state._file:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000100 raise RuntimeError, "input() already active"
Guido van Rossum47955242001-01-05 14:44:39 +0000101 _state = FileInput(files, inplace, backup, bufsize)
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000102 return _state
103
104def close():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000105 """Close the sequence."""
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000106 global _state
107 state = _state
108 _state = None
109 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000110 state.close()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000111
112def nextfile():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000113 """
114 Close the current file so that the next iteration will read the first
115 line from the next file (if any); lines not read from the file will
116 not count towards the cumulative line count. The filename is not
117 changed until after the first line of the next file has been read.
118 Before the first line has been read, this function has no effect;
119 it cannot be used to skip the first file. After the last line of the
Tim Peters8ac14952002-05-23 15:15:30 +0000120 last file has been read, this function has no effect.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000121 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000122 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000123 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000124 return _state.nextfile()
125
126def filename():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000127 """
128 Return the name of the file currently being read.
Tim Peters8ac14952002-05-23 15:15:30 +0000129 Before the first line has been read, returns None.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000130 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000131 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000132 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000133 return _state.filename()
134
135def lineno():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000136 """
137 Return the cumulative line number of the line that has just been read.
138 Before the first line has been read, returns 0. After the last line
Tim Peters8ac14952002-05-23 15:15:30 +0000139 of the last file has been read, returns the line number of that line.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000140 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000141 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000142 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000143 return _state.lineno()
144
145def filelineno():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000146 """
147 Return the line number in the current file. Before the first line
148 has been read, returns 0. After the last line of the last file has
Tim Peters8ac14952002-05-23 15:15:30 +0000149 been read, returns the line number of that line within the file.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000150 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000151 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000152 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000153 return _state.filelineno()
154
Georg Brandl67e9fb92006-02-19 13:56:17 +0000155def fileno():
156 """
157 Return the file number of the current file. When no file is currently
158 opened, returns -1.
159 """
160 if not _state:
161 raise RuntimeError, "no active input()"
162 return _state.fileno()
163
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000164def isfirstline():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000165 """
166 Returns true the line just read is the first line of its file,
Tim Peters8ac14952002-05-23 15:15:30 +0000167 otherwise returns false.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000168 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000169 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000170 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000171 return _state.isfirstline()
172
173def isstdin():
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000174 """
175 Returns true if the last line was read from sys.stdin,
Tim Peters8ac14952002-05-23 15:15:30 +0000176 otherwise returns false.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000177 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000178 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000179 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000180 return _state.isstdin()
181
182class FileInput:
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000183 """class FileInput([files[, inplace[, backup]]])
Tim Peters8ac14952002-05-23 15:15:30 +0000184
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000185 Class FileInput is the implementation of the module; its methods
Georg Brandl67e9fb92006-02-19 13:56:17 +0000186 filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
187 nextfile() and close() correspond to the functions of the same name
188 in the module.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000189 In addition it has a readline() method which returns the next
190 input line, and a __getitem__() method which implements the
191 sequence behavior. The sequence must be accessed in strictly
Tim Peters8ac14952002-05-23 15:15:30 +0000192 sequential order; random access and readline() cannot be mixed.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000193 """
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000194
Guido van Rossum47955242001-01-05 14:44:39 +0000195 def __init__(self, files=None, inplace=0, backup="", bufsize=0):
Georg Brandle4662172006-02-19 09:51:27 +0000196 if isinstance(files, basestring):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000197 files = (files,)
198 else:
Guido van Rossum2516b392000-04-10 17:16:12 +0000199 if files is None:
200 files = sys.argv[1:]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000201 if not files:
Guido van Rossum2516b392000-04-10 17:16:12 +0000202 files = ('-',)
203 else:
204 files = tuple(files)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000205 self._files = files
206 self._inplace = inplace
207 self._backup = backup
Guido van Rossum47955242001-01-05 14:44:39 +0000208 self._bufsize = bufsize or DEFAULT_BUFSIZE
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000209 self._savestdout = None
210 self._output = None
211 self._filename = None
212 self._lineno = 0
213 self._filelineno = 0
214 self._file = None
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000215 self._isstdin = False
Guido van Rossum0aec9fb1998-07-20 15:49:28 +0000216 self._backupfilename = None
Guido van Rossum47955242001-01-05 14:44:39 +0000217 self._buffer = []
218 self._bufindex = 0
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000219
220 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000221 self.close()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000222
223 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000224 self.nextfile()
225 self._files = ()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000226
Neil Schemenauer908632a2002-03-26 20:28:40 +0000227 def __iter__(self):
228 return self
229
230 def next(self):
Guido van Rossum47955242001-01-05 14:44:39 +0000231 try:
232 line = self._buffer[self._bufindex]
233 except IndexError:
234 pass
235 else:
236 self._bufindex += 1
237 self._lineno += 1
238 self._filelineno += 1
239 return line
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000240 line = self.readline()
241 if not line:
Neil Schemenauer908632a2002-03-26 20:28:40 +0000242 raise StopIteration
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000243 return line
Tim Peters863ac442002-04-16 01:38:40 +0000244
Neil Schemenauer908632a2002-03-26 20:28:40 +0000245 def __getitem__(self, i):
246 if i != self._lineno:
247 raise RuntimeError, "accessing lines out of order"
248 try:
249 return self.next()
250 except StopIteration:
251 raise IndexError, "end of input reached"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000252
253 def nextfile(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000254 savestdout = self._savestdout
255 self._savestdout = 0
256 if savestdout:
257 sys.stdout = savestdout
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000258
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000259 output = self._output
260 self._output = 0
261 if output:
262 output.close()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000263
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000264 file = self._file
265 self._file = 0
266 if file and not self._isstdin:
267 file.close()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000268
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000269 backupfilename = self._backupfilename
270 self._backupfilename = 0
271 if backupfilename and not self._backup:
272 try: os.unlink(backupfilename)
Skip Montanarocffac662002-08-14 02:58:16 +0000273 except OSError: pass
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000274
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000275 self._isstdin = False
Guido van Rossum47955242001-01-05 14:44:39 +0000276 self._buffer = []
277 self._bufindex = 0
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000278
279 def readline(self):
Guido van Rossum47955242001-01-05 14:44:39 +0000280 try:
281 line = self._buffer[self._bufindex]
282 except IndexError:
283 pass
284 else:
285 self._bufindex += 1
286 self._lineno += 1
287 self._filelineno += 1
288 return line
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000289 if not self._file:
290 if not self._files:
291 return ""
292 self._filename = self._files[0]
293 self._files = self._files[1:]
294 self._filelineno = 0
295 self._file = None
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000296 self._isstdin = False
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000297 self._backupfilename = 0
298 if self._filename == '-':
299 self._filename = '<stdin>'
300 self._file = sys.stdin
Guido van Rossum8ca162f2002-04-07 06:36:23 +0000301 self._isstdin = True
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000302 else:
303 if self._inplace:
304 self._backupfilename = (
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000305 self._filename + (self._backup or os.extsep+"bak"))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000306 try: os.unlink(self._backupfilename)
307 except os.error: pass
Guido van Rossumdcb85831999-10-18 21:41:43 +0000308 # The next few lines may raise IOError
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000309 os.rename(self._filename, self._backupfilename)
310 self._file = open(self._backupfilename, "r")
Guido van Rossumdcb85831999-10-18 21:41:43 +0000311 try:
Walter Dörwald294bbf32002-06-06 09:48:13 +0000312 perm = os.fstat(self._file.fileno()).st_mode
Skip Montanarocffac662002-08-14 02:58:16 +0000313 except OSError:
Guido van Rossumdcb85831999-10-18 21:41:43 +0000314 self._output = open(self._filename, "w")
315 else:
316 fd = os.open(self._filename,
317 os.O_CREAT | os.O_WRONLY | os.O_TRUNC,
318 perm)
319 self._output = os.fdopen(fd, "w")
320 try:
Jack Jansen52941a82003-01-08 16:33:16 +0000321 if hasattr(os, 'chmod'):
322 os.chmod(self._filename, perm)
Skip Montanarocffac662002-08-14 02:58:16 +0000323 except OSError:
Guido van Rossumdcb85831999-10-18 21:41:43 +0000324 pass
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000325 self._savestdout = sys.stdout
326 sys.stdout = self._output
327 else:
328 # This may raise IOError
329 self._file = open(self._filename, "r")
Guido van Rossum47955242001-01-05 14:44:39 +0000330 self._buffer = self._file.readlines(self._bufsize)
331 self._bufindex = 0
332 if not self._buffer:
333 self.nextfile()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000334 # Recursive call
335 return self.readline()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000336
337 def filename(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000338 return self._filename
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000339
340 def lineno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000341 return self._lineno
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000342
343 def filelineno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000344 return self._filelineno
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000345
Georg Brandl67e9fb92006-02-19 13:56:17 +0000346 def fileno(self):
347 if self._file:
348 try:
349 return self._file.fileno()
350 except ValueError:
351 return -1
352 else:
353 return -1
354
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000355 def isfirstline(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000356 return self._filelineno == 1
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000357
358 def isstdin(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000359 return self._isstdin
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000360
361def _test():
362 import getopt
363 inplace = 0
364 backup = 0
365 opts, args = getopt.getopt(sys.argv[1:], "ib:")
366 for o, a in opts:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000367 if o == '-i': inplace = 1
368 if o == '-b': backup = a
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000369 for line in input(args, inplace=inplace, backup=backup):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000370 if line[-1:] == '\n': line = line[:-1]
371 if line[-1:] == '\r': line = line[:-1]
372 print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
373 isfirstline() and "*" or "", line)
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000374 print "%d: %s[%d]" % (lineno(), filename(), filelineno())
375
376if __name__ == '__main__':
377 _test()