Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 1 | """Helper class to quickly write a loop over all standard input files. |
| 2 | |
| 3 | Typical use is: |
| 4 | |
| 5 | import fileinput |
| 6 | for line in fileinput.input(): |
| 7 | process(line) |
| 8 | |
| 9 | This iterates over the lines of all files listed in sys.argv[1:], |
| 10 | defaulting to sys.stdin if the list is empty. If a filename is '-' it |
Michele Angrisano | aca273e | 2019-06-02 23:01:49 +0200 | [diff] [blame] | 11 | is also replaced by sys.stdin and the optional arguments mode and |
| 12 | openhook are ignored. To specify an alternative list of filenames, |
| 13 | pass it as the argument to input(). A single file name is also allowed. |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 14 | |
| 15 | Functions filename(), lineno() return the filename and cumulative line |
| 16 | number of the line that has just been read; filelineno() returns its |
| 17 | line number in the current file; isfirstline() returns true iff the |
| 18 | line just read is the first line of its file; isstdin() returns true |
| 19 | iff the line was read from sys.stdin. Function nextfile() closes the |
| 20 | current file so that the next iteration will read the first line from |
| 21 | the next file (if any); lines not read from the file will not count |
| 22 | towards the cumulative line count; the filename is not changed until |
| 23 | after the first line of the next file has been read. Function close() |
| 24 | closes the sequence. |
| 25 | |
| 26 | Before any lines have been read, filename() returns None and both line |
| 27 | numbers are zero; nextfile() has no effect. After all lines have been |
| 28 | read, filename() and the line number functions return the values |
| 29 | pertaining to the last line read; nextfile() has no effect. |
| 30 | |
Georg Brandl | c029f87 | 2006-02-19 14:12:34 +0000 | [diff] [blame] | 31 | All files are opened in text mode by default, you can override this by |
| 32 | setting the mode parameter to input() or FileInput.__init__(). |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 33 | If an I/O error occurs during opening or reading a file, the OSError |
Georg Brandl | c029f87 | 2006-02-19 14:12:34 +0000 | [diff] [blame] | 34 | exception is raised. |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 35 | |
| 36 | If sys.stdin is used more than once, the second and further use will |
| 37 | return no lines, except perhaps for interactive use, or if it has been |
| 38 | explicitly reset (e.g. using sys.stdin.seek(0)). |
| 39 | |
| 40 | Empty files are opened and immediately closed; the only time their |
| 41 | presence in the list of filenames is noticeable at all is when the |
| 42 | last file opened is empty. |
| 43 | |
| 44 | It is possible that the last line of a file doesn't end in a newline |
| 45 | character; otherwise lines are returned including the trailing |
| 46 | newline. |
| 47 | |
| 48 | Class FileInput is the implementation; its methods filename(), |
| 49 | lineno(), fileline(), isfirstline(), isstdin(), nextfile() and close() |
| 50 | correspond to the functions in the module. In addition it has a |
| 51 | readline() method which returns the next input line, and a |
| 52 | __getitem__() method which implements the sequence behavior. The |
| 53 | sequence must be accessed in strictly sequential order; sequence |
| 54 | access and readline() cannot be mixed. |
| 55 | |
| 56 | Optional in-place filtering: if the keyword argument inplace=1 is |
| 57 | passed to input() or to the FileInput constructor, the file is moved |
| 58 | to a backup file and standard output is directed to the input file. |
| 59 | This makes it possible to write a filter that rewrites its input file |
| 60 | in place. If the keyword argument backup=".<some extension>" is also |
| 61 | given, it specifies the extension for the backup file, and the backup |
| 62 | file remains around; by default, the extension is ".bak" and it is |
| 63 | deleted when the output file is closed. In-place filtering is |
| 64 | disabled when standard input is read. XXX The current implementation |
| 65 | does not work for MS-DOS 8+3 filesystems. |
| 66 | |
| 67 | XXX Possible additions: |
| 68 | |
| 69 | - optional getopt argument processing |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 70 | - isatty() |
| 71 | - read(), read(size), even readlines() |
| 72 | |
| 73 | """ |
| 74 | |
Walter Dörwald | 294bbf3 | 2002-06-06 09:48:13 +0000 | [diff] [blame] | 75 | import sys, os |
Ethan Smith | e3ec44d | 2020-04-09 21:47:31 -0700 | [diff] [blame] | 76 | from types import GenericAlias |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 77 | |
Georg Brandl | ef0a865 | 2009-05-17 12:22:57 +0000 | [diff] [blame] | 78 | __all__ = ["input", "close", "nextfile", "filename", "lineno", "filelineno", |
Martin Panter | 7978e10 | 2016-01-16 06:26:54 +0000 | [diff] [blame] | 79 | "fileno", "isfirstline", "isstdin", "FileInput", "hook_compressed", |
| 80 | "hook_encoded"] |
Skip Montanaro | eccd02a | 2001-01-20 23:34:12 +0000 | [diff] [blame] | 81 | |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 82 | _state = None |
| 83 | |
Matthias Bussonnier | 1a3faf9 | 2019-05-20 13:44:11 -0700 | [diff] [blame] | 84 | def input(files=None, inplace=False, backup="", *, mode="r", openhook=None): |
Terry Jan Reedy | 70d2c71 | 2013-06-28 18:59:28 -0400 | [diff] [blame] | 85 | """Return an instance of the FileInput class, which can be iterated. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 86 | |
Terry Jan Reedy | 70d2c71 | 2013-06-28 18:59:28 -0400 | [diff] [blame] | 87 | The parameters are passed to the constructor of the FileInput class. |
| 88 | The returned instance, in addition to being an iterator, |
| 89 | keeps global state for the functions of this module,. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 90 | """ |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 91 | global _state |
| 92 | if _state and _state._file: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 93 | raise RuntimeError("input() already active") |
Matthias Bussonnier | 1a3faf9 | 2019-05-20 13:44:11 -0700 | [diff] [blame] | 94 | _state = FileInput(files, inplace, backup, mode=mode, openhook=openhook) |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 95 | return _state |
| 96 | |
| 97 | def close(): |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 98 | """Close the sequence.""" |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 99 | global _state |
| 100 | state = _state |
| 101 | _state = None |
| 102 | if state: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 103 | state.close() |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 104 | |
| 105 | def nextfile(): |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 106 | """ |
| 107 | Close the current file so that the next iteration will read the first |
| 108 | line from the next file (if any); lines not read from the file will |
| 109 | not count towards the cumulative line count. The filename is not |
| 110 | changed until after the first line of the next file has been read. |
| 111 | Before the first line has been read, this function has no effect; |
| 112 | it cannot be used to skip the first file. After the last line of the |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 113 | last file has been read, this function has no effect. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 114 | """ |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 115 | if not _state: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 116 | raise RuntimeError("no active input()") |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 117 | return _state.nextfile() |
| 118 | |
| 119 | def filename(): |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 120 | """ |
| 121 | Return the name of the file currently being read. |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 122 | Before the first line has been read, returns None. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 123 | """ |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 124 | if not _state: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 125 | raise RuntimeError("no active input()") |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 126 | return _state.filename() |
| 127 | |
| 128 | def lineno(): |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 129 | """ |
| 130 | Return the cumulative line number of the line that has just been read. |
| 131 | Before the first line has been read, returns 0. After the last line |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 132 | of the last file has been read, returns the line number of that line. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 133 | """ |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 134 | if not _state: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 135 | raise RuntimeError("no active input()") |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 136 | return _state.lineno() |
| 137 | |
| 138 | def filelineno(): |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 139 | """ |
| 140 | Return the line number in the current file. Before the first line |
| 141 | has been read, returns 0. After the last line of the last file has |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 142 | been read, returns the line number of that line within the file. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 143 | """ |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 144 | if not _state: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 145 | raise RuntimeError("no active input()") |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 146 | return _state.filelineno() |
| 147 | |
Georg Brandl | 67e9fb9 | 2006-02-19 13:56:17 +0000 | [diff] [blame] | 148 | def fileno(): |
| 149 | """ |
| 150 | Return the file number of the current file. When no file is currently |
| 151 | opened, returns -1. |
| 152 | """ |
| 153 | if not _state: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 154 | raise RuntimeError("no active input()") |
Georg Brandl | 67e9fb9 | 2006-02-19 13:56:17 +0000 | [diff] [blame] | 155 | return _state.fileno() |
| 156 | |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 157 | def isfirstline(): |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 158 | """ |
| 159 | Returns true the line just read is the first line of its file, |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 160 | otherwise returns false. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 161 | """ |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 162 | if not _state: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 163 | raise RuntimeError("no active input()") |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 164 | return _state.isfirstline() |
| 165 | |
| 166 | def isstdin(): |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 167 | """ |
| 168 | Returns true if the last line was read from sys.stdin, |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 169 | otherwise returns false. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 170 | """ |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 171 | if not _state: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 172 | raise RuntimeError("no active input()") |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 173 | return _state.isstdin() |
| 174 | |
| 175 | class FileInput: |
Matthias Bussonnier | 1a3faf9 | 2019-05-20 13:44:11 -0700 | [diff] [blame] | 176 | """FileInput([files[, inplace[, backup]]], *, mode=None, openhook=None) |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 177 | |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 178 | Class FileInput is the implementation of the module; its methods |
Georg Brandl | 67e9fb9 | 2006-02-19 13:56:17 +0000 | [diff] [blame] | 179 | filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(), |
| 180 | nextfile() and close() correspond to the functions of the same name |
| 181 | in the module. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 182 | In addition it has a readline() method which returns the next |
| 183 | input line, and a __getitem__() method which implements the |
| 184 | sequence behavior. The sequence must be accessed in strictly |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 185 | sequential order; random access and readline() cannot be mixed. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 186 | """ |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 187 | |
Matthias Bussonnier | 1a3faf9 | 2019-05-20 13:44:11 -0700 | [diff] [blame] | 188 | def __init__(self, files=None, inplace=False, backup="", *, |
Georg Brandl | c98eeed | 2006-02-19 14:57:47 +0000 | [diff] [blame] | 189 | mode="r", openhook=None): |
Guido van Rossum | 3172c5d | 2007-10-16 18:12:55 +0000 | [diff] [blame] | 190 | if isinstance(files, str): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 191 | files = (files,) |
Roy Williams | 002665a | 2017-05-22 22:24:17 -0700 | [diff] [blame] | 192 | elif isinstance(files, os.PathLike): |
| 193 | files = (os.fspath(files), ) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 194 | else: |
Guido van Rossum | 2516b39 | 2000-04-10 17:16:12 +0000 | [diff] [blame] | 195 | if files is None: |
| 196 | files = sys.argv[1:] |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 197 | if not files: |
Guido van Rossum | 2516b39 | 2000-04-10 17:16:12 +0000 | [diff] [blame] | 198 | files = ('-',) |
| 199 | else: |
| 200 | files = tuple(files) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 201 | self._files = files |
| 202 | self._inplace = inplace |
| 203 | self._backup = backup |
| 204 | self._savestdout = None |
| 205 | self._output = None |
| 206 | self._filename = None |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 207 | self._startlineno = 0 |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 208 | self._filelineno = 0 |
| 209 | self._file = None |
Guido van Rossum | 8ca162f | 2002-04-07 06:36:23 +0000 | [diff] [blame] | 210 | self._isstdin = False |
Guido van Rossum | 0aec9fb | 1998-07-20 15:49:28 +0000 | [diff] [blame] | 211 | self._backupfilename = None |
Georg Brandl | c029f87 | 2006-02-19 14:12:34 +0000 | [diff] [blame] | 212 | # restrict mode argument to reading modes |
Victor Stinner | 942f7a2 | 2020-03-04 18:50:22 +0100 | [diff] [blame] | 213 | if mode not in ('r', 'rU', 'U', 'rb'): |
| 214 | raise ValueError("FileInput opening mode must be one of " |
| 215 | "'r', 'rU', 'U' and 'rb'") |
| 216 | if 'U' in mode: |
| 217 | import warnings |
| 218 | warnings.warn("'U' mode is deprecated", |
| 219 | DeprecationWarning, 2) |
Georg Brandl | c029f87 | 2006-02-19 14:12:34 +0000 | [diff] [blame] | 220 | self._mode = mode |
Victor Stinner | 942f7a2 | 2020-03-04 18:50:22 +0100 | [diff] [blame] | 221 | self._write_mode = mode.replace('r', 'w') if 'U' not in mode else 'w' |
Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 222 | if openhook: |
| 223 | if inplace: |
| 224 | raise ValueError("FileInput cannot use an opening hook in inplace mode") |
| 225 | if not callable(openhook): |
| 226 | raise ValueError("FileInput openhook must be callable") |
Georg Brandl | c98eeed | 2006-02-19 14:57:47 +0000 | [diff] [blame] | 227 | self._openhook = openhook |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 228 | |
| 229 | def __del__(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 230 | self.close() |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 231 | |
| 232 | def close(self): |
Serhiy Storchaka | 7e7a3db | 2015-04-10 13:24:41 +0300 | [diff] [blame] | 233 | try: |
| 234 | self.nextfile() |
| 235 | finally: |
| 236 | self._files = () |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 237 | |
Georg Brandl | 6cb7b65 | 2010-07-31 20:08:15 +0000 | [diff] [blame] | 238 | def __enter__(self): |
| 239 | return self |
| 240 | |
| 241 | def __exit__(self, type, value, traceback): |
| 242 | self.close() |
| 243 | |
Neil Schemenauer | 908632a | 2002-03-26 20:28:40 +0000 | [diff] [blame] | 244 | def __iter__(self): |
| 245 | return self |
| 246 | |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 247 | def __next__(self): |
Serhiy Storchaka | 0554d83 | 2016-03-08 23:35:35 +0200 | [diff] [blame] | 248 | while True: |
| 249 | line = self._readline() |
| 250 | if line: |
| 251 | self._filelineno += 1 |
| 252 | return line |
| 253 | if not self._file: |
| 254 | raise StopIteration |
| 255 | self.nextfile() |
| 256 | # repeat with next file |
Tim Peters | 863ac44 | 2002-04-16 01:38:40 +0000 | [diff] [blame] | 257 | |
Neil Schemenauer | 908632a | 2002-03-26 20:28:40 +0000 | [diff] [blame] | 258 | def __getitem__(self, i): |
Berker Peksag | 84a13fb | 2018-08-11 09:05:04 +0300 | [diff] [blame] | 259 | import warnings |
| 260 | warnings.warn( |
| 261 | "Support for indexing FileInput objects is deprecated. " |
| 262 | "Use iterator protocol instead.", |
| 263 | DeprecationWarning, |
| 264 | stacklevel=2 |
| 265 | ) |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 266 | if i != self.lineno(): |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 267 | raise RuntimeError("accessing lines out of order") |
Neil Schemenauer | 908632a | 2002-03-26 20:28:40 +0000 | [diff] [blame] | 268 | try: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 269 | return self.__next__() |
Neil Schemenauer | 908632a | 2002-03-26 20:28:40 +0000 | [diff] [blame] | 270 | except StopIteration: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 271 | raise IndexError("end of input reached") |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 272 | |
| 273 | def nextfile(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 274 | savestdout = self._savestdout |
Serhiy Storchaka | 2116b12 | 2015-04-10 13:29:28 +0300 | [diff] [blame] | 275 | self._savestdout = None |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 276 | if savestdout: |
| 277 | sys.stdout = savestdout |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 278 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 279 | output = self._output |
Serhiy Storchaka | 2116b12 | 2015-04-10 13:29:28 +0300 | [diff] [blame] | 280 | self._output = None |
Serhiy Storchaka | 7e7a3db | 2015-04-10 13:24:41 +0300 | [diff] [blame] | 281 | try: |
| 282 | if output: |
| 283 | output.close() |
| 284 | finally: |
| 285 | file = self._file |
Serhiy Storchaka | 2116b12 | 2015-04-10 13:29:28 +0300 | [diff] [blame] | 286 | self._file = None |
Serhiy Storchaka | 0554d83 | 2016-03-08 23:35:35 +0200 | [diff] [blame] | 287 | try: |
| 288 | del self._readline # restore FileInput._readline |
| 289 | except AttributeError: |
| 290 | pass |
Serhiy Storchaka | 7e7a3db | 2015-04-10 13:24:41 +0300 | [diff] [blame] | 291 | try: |
| 292 | if file and not self._isstdin: |
| 293 | file.close() |
| 294 | finally: |
| 295 | backupfilename = self._backupfilename |
Serhiy Storchaka | 2116b12 | 2015-04-10 13:29:28 +0300 | [diff] [blame] | 296 | self._backupfilename = None |
Serhiy Storchaka | 7e7a3db | 2015-04-10 13:24:41 +0300 | [diff] [blame] | 297 | if backupfilename and not self._backup: |
| 298 | try: os.unlink(backupfilename) |
| 299 | except OSError: pass |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 300 | |
Serhiy Storchaka | 7e7a3db | 2015-04-10 13:24:41 +0300 | [diff] [blame] | 301 | self._isstdin = False |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 302 | |
| 303 | def readline(self): |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 304 | while True: |
| 305 | line = self._readline() |
| 306 | if line: |
| 307 | self._filelineno += 1 |
| 308 | return line |
| 309 | if not self._file: |
| 310 | return line |
| 311 | self.nextfile() |
| 312 | # repeat with next file |
| 313 | |
Serhiy Storchaka | 0554d83 | 2016-03-08 23:35:35 +0200 | [diff] [blame] | 314 | def _readline(self): |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 315 | if not self._files: |
| 316 | if 'b' in self._mode: |
| 317 | return b'' |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 318 | else: |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 319 | return '' |
| 320 | self._filename = self._files[0] |
| 321 | self._files = self._files[1:] |
| 322 | self._startlineno = self.lineno() |
| 323 | self._filelineno = 0 |
| 324 | self._file = None |
| 325 | self._isstdin = False |
| 326 | self._backupfilename = 0 |
| 327 | if self._filename == '-': |
| 328 | self._filename = '<stdin>' |
| 329 | if 'b' in self._mode: |
| 330 | self._file = getattr(sys.stdin, 'buffer', sys.stdin) |
| 331 | else: |
| 332 | self._file = sys.stdin |
| 333 | self._isstdin = True |
| 334 | else: |
| 335 | if self._inplace: |
| 336 | self._backupfilename = ( |
Zhiming Wang | 06de1ae | 2017-09-05 01:37:24 +0800 | [diff] [blame] | 337 | os.fspath(self._filename) + (self._backup or ".bak")) |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 338 | try: |
| 339 | os.unlink(self._backupfilename) |
| 340 | except OSError: |
| 341 | pass |
| 342 | # The next few lines may raise OSError |
| 343 | os.rename(self._filename, self._backupfilename) |
| 344 | self._file = open(self._backupfilename, self._mode) |
| 345 | try: |
| 346 | perm = os.fstat(self._file.fileno()).st_mode |
| 347 | except OSError: |
Berker Peksag | be6dbfb | 2019-04-29 17:55:39 +0300 | [diff] [blame] | 348 | self._output = open(self._filename, self._write_mode) |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 349 | else: |
| 350 | mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC |
| 351 | if hasattr(os, 'O_BINARY'): |
| 352 | mode |= os.O_BINARY |
| 353 | |
| 354 | fd = os.open(self._filename, mode, perm) |
Berker Peksag | be6dbfb | 2019-04-29 17:55:39 +0300 | [diff] [blame] | 355 | self._output = os.fdopen(fd, self._write_mode) |
Andrew Svetlov | ad28c7f | 2012-12-18 22:02:39 +0200 | [diff] [blame] | 356 | try: |
Anthony Sottile | 8377cd4 | 2019-02-25 14:32:27 -0800 | [diff] [blame] | 357 | os.chmod(self._filename, perm) |
Andrew Svetlov | ad28c7f | 2012-12-18 22:02:39 +0200 | [diff] [blame] | 358 | except OSError: |
| 359 | pass |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 360 | self._savestdout = sys.stdout |
| 361 | sys.stdout = self._output |
| 362 | else: |
| 363 | # This may raise OSError |
| 364 | if self._openhook: |
| 365 | self._file = self._openhook(self._filename, self._mode) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 366 | else: |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 367 | self._file = open(self._filename, self._mode) |
Serhiy Storchaka | 0554d83 | 2016-03-08 23:35:35 +0200 | [diff] [blame] | 368 | self._readline = self._file.readline # hide FileInput._readline |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 369 | return self._readline() |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 370 | |
| 371 | def filename(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 372 | return self._filename |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 373 | |
| 374 | def lineno(self): |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 375 | return self._startlineno + self._filelineno |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 376 | |
| 377 | def filelineno(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 378 | return self._filelineno |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 379 | |
Georg Brandl | 67e9fb9 | 2006-02-19 13:56:17 +0000 | [diff] [blame] | 380 | def fileno(self): |
| 381 | if self._file: |
| 382 | try: |
| 383 | return self._file.fileno() |
| 384 | except ValueError: |
| 385 | return -1 |
| 386 | else: |
| 387 | return -1 |
| 388 | |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 389 | def isfirstline(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 390 | return self._filelineno == 1 |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 391 | |
| 392 | def isstdin(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 393 | return self._isstdin |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 394 | |
Ethan Smith | e3ec44d | 2020-04-09 21:47:31 -0700 | [diff] [blame] | 395 | __class_getitem__ = classmethod(GenericAlias) |
| 396 | |
Georg Brandl | c98eeed | 2006-02-19 14:57:47 +0000 | [diff] [blame] | 397 | |
| 398 | def hook_compressed(filename, mode): |
| 399 | ext = os.path.splitext(filename)[1] |
| 400 | if ext == '.gz': |
| 401 | import gzip |
| 402 | return gzip.open(filename, mode) |
| 403 | elif ext == '.bz2': |
| 404 | import bz2 |
| 405 | return bz2.BZ2File(filename, mode) |
| 406 | else: |
| 407 | return open(filename, mode) |
| 408 | |
| 409 | |
Serhiy Storchaka | b275210 | 2016-04-27 23:13:46 +0300 | [diff] [blame] | 410 | def hook_encoded(encoding, errors=None): |
Georg Brandl | c98eeed | 2006-02-19 14:57:47 +0000 | [diff] [blame] | 411 | def openhook(filename, mode): |
Serhiy Storchaka | b275210 | 2016-04-27 23:13:46 +0300 | [diff] [blame] | 412 | return open(filename, mode, encoding=encoding, errors=errors) |
Georg Brandl | c98eeed | 2006-02-19 14:57:47 +0000 | [diff] [blame] | 413 | return openhook |
| 414 | |
| 415 | |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 416 | def _test(): |
| 417 | import getopt |
Georg Brandl | ef0a865 | 2009-05-17 12:22:57 +0000 | [diff] [blame] | 418 | inplace = False |
| 419 | backup = False |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 420 | opts, args = getopt.getopt(sys.argv[1:], "ib:") |
| 421 | for o, a in opts: |
Georg Brandl | ef0a865 | 2009-05-17 12:22:57 +0000 | [diff] [blame] | 422 | if o == '-i': inplace = True |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 423 | if o == '-b': backup = a |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 424 | for line in input(args, inplace=inplace, backup=backup): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 425 | if line[-1:] == '\n': line = line[:-1] |
| 426 | if line[-1:] == '\r': line = line[:-1] |
Guido van Rossum | be19ed7 | 2007-02-09 05:37:30 +0000 | [diff] [blame] | 427 | print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(), |
| 428 | isfirstline() and "*" or "", line)) |
| 429 | print("%d: %s[%d]" % (lineno(), filename(), filelineno())) |
Guido van Rossum | 7d5b99d | 1997-11-21 17:12:59 +0000 | [diff] [blame] | 430 | |
| 431 | if __name__ == '__main__': |
| 432 | _test() |