blob: 2e26b5b2cd90814473031090da8e5ddb520f7ec4 [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
65XXX Possible additions:
66
67- optional getopt argument processing
68- specify open mode ('r' or 'rb')
69- specify buffer size
70- fileno()
71- isatty()
72- read(), read(size), even readlines()
73
74"""
75
76import sys, os
77
78_state = None
79
80def input(files=(), inplace=0, backup=""):
81 global _state
82 if _state and _state._file:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000083 raise RuntimeError, "input() already active"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000084 _state = FileInput(files, inplace, backup)
85 return _state
86
87def close():
88 global _state
89 state = _state
90 _state = None
91 if state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000092 state.close()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000093
94def nextfile():
95 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000096 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +000097 return _state.nextfile()
98
99def filename():
100 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000101 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000102 return _state.filename()
103
104def lineno():
105 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000106 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000107 return _state.lineno()
108
109def filelineno():
110 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000112 return _state.filelineno()
113
114def isfirstline():
115 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000116 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000117 return _state.isfirstline()
118
119def isstdin():
120 if not _state:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000121 raise RuntimeError, "no active input()"
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000122 return _state.isstdin()
123
124class FileInput:
125
126 def __init__(self, files=(), inplace=0, backup=""):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000127 if type(files) == type(''):
128 files = (files,)
129 else:
130 files = tuple(files)
131 if not files:
132 files = tuple(sys.argv[1:])
133 if not files:
134 files = ('-',)
135 self._files = files
136 self._inplace = inplace
137 self._backup = backup
138 self._savestdout = None
139 self._output = None
140 self._filename = None
141 self._lineno = 0
142 self._filelineno = 0
143 self._file = None
144 self._isstdin = 0
Guido van Rossum0aec9fb1998-07-20 15:49:28 +0000145 self._backupfilename = None
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000146
147 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000148 self.close()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000149
150 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000151 self.nextfile()
152 self._files = ()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000153
154 def __getitem__(self, i):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000155 if i != self._lineno:
156 raise RuntimeError, "accessing lines out of order"
157 line = self.readline()
158 if not line:
159 raise IndexError, "end of input reached"
160 return line
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000161
162 def nextfile(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000163 savestdout = self._savestdout
164 self._savestdout = 0
165 if savestdout:
166 sys.stdout = savestdout
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000167
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000168 output = self._output
169 self._output = 0
170 if output:
171 output.close()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000172
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000173 file = self._file
174 self._file = 0
175 if file and not self._isstdin:
176 file.close()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000177
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 backupfilename = self._backupfilename
179 self._backupfilename = 0
180 if backupfilename and not self._backup:
181 try: os.unlink(backupfilename)
182 except: pass
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000183
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000184 self._isstdin = 0
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000185
186 def readline(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000187 if not self._file:
188 if not self._files:
189 return ""
190 self._filename = self._files[0]
191 self._files = self._files[1:]
192 self._filelineno = 0
193 self._file = None
194 self._isstdin = 0
195 self._backupfilename = 0
196 if self._filename == '-':
197 self._filename = '<stdin>'
198 self._file = sys.stdin
199 self._isstdin = 1
200 else:
201 if self._inplace:
202 self._backupfilename = (
203 self._filename + (self._backup or ".bak"))
204 try: os.unlink(self._backupfilename)
205 except os.error: pass
206 # The next three lines may raise IOError
207 os.rename(self._filename, self._backupfilename)
208 self._file = open(self._backupfilename, "r")
209 self._output = open(self._filename, "w")
210 self._savestdout = sys.stdout
211 sys.stdout = self._output
212 else:
213 # This may raise IOError
214 self._file = open(self._filename, "r")
215 line = self._file.readline()
216 if line:
217 self._lineno = self._lineno + 1
218 self._filelineno = self._filelineno + 1
219 return line
220 self.nextfile()
221 # Recursive call
222 return self.readline()
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000223
224 def filename(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000225 return self._filename
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000226
227 def lineno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000228 return self._lineno
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000229
230 def filelineno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000231 return self._filelineno
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000232
233 def isfirstline(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000234 return self._filelineno == 1
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000235
236 def isstdin(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000237 return self._isstdin
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000238
239def _test():
240 import getopt
241 inplace = 0
242 backup = 0
243 opts, args = getopt.getopt(sys.argv[1:], "ib:")
244 for o, a in opts:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000245 if o == '-i': inplace = 1
246 if o == '-b': backup = a
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000247 for line in input(args, inplace=inplace, backup=backup):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000248 if line[-1:] == '\n': line = line[:-1]
249 if line[-1:] == '\r': line = line[:-1]
250 print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
251 isfirstline() and "*" or "", line)
Guido van Rossum7d5b99d1997-11-21 17:12:59 +0000252 print "%d: %s[%d]" % (lineno(), filename(), filelineno())
253
254if __name__ == '__main__':
255 _test()