Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ExeBy/smexe_ro.../lib64/python2....
File: fileinput.py
"""Helper class to quickly write a loop over all standard input files.
[0] Fix | Delete
[1] Fix | Delete
Typical use is:
[2] Fix | Delete
[3] Fix | Delete
import fileinput
[4] Fix | Delete
for line in fileinput.input():
[5] Fix | Delete
process(line)
[6] Fix | Delete
[7] Fix | Delete
This iterates over the lines of all files listed in sys.argv[1:],
[8] Fix | Delete
defaulting to sys.stdin if the list is empty. If a filename is '-' it
[9] Fix | Delete
is also replaced by sys.stdin. To specify an alternative list of
[10] Fix | Delete
filenames, pass it as the argument to input(). A single file name is
[11] Fix | Delete
also allowed.
[12] Fix | Delete
[13] Fix | Delete
Functions filename(), lineno() return the filename and cumulative line
[14] Fix | Delete
number of the line that has just been read; filelineno() returns its
[15] Fix | Delete
line number in the current file; isfirstline() returns true iff the
[16] Fix | Delete
line just read is the first line of its file; isstdin() returns true
[17] Fix | Delete
iff the line was read from sys.stdin. Function nextfile() closes the
[18] Fix | Delete
current file so that the next iteration will read the first line from
[19] Fix | Delete
the next file (if any); lines not read from the file will not count
[20] Fix | Delete
towards the cumulative line count; the filename is not changed until
[21] Fix | Delete
after the first line of the next file has been read. Function close()
[22] Fix | Delete
closes the sequence.
[23] Fix | Delete
[24] Fix | Delete
Before any lines have been read, filename() returns None and both line
[25] Fix | Delete
numbers are zero; nextfile() has no effect. After all lines have been
[26] Fix | Delete
read, filename() and the line number functions return the values
[27] Fix | Delete
pertaining to the last line read; nextfile() has no effect.
[28] Fix | Delete
[29] Fix | Delete
All files are opened in text mode by default, you can override this by
[30] Fix | Delete
setting the mode parameter to input() or FileInput.__init__().
[31] Fix | Delete
If an I/O error occurs during opening or reading a file, the IOError
[32] Fix | Delete
exception is raised.
[33] Fix | Delete
[34] Fix | Delete
If sys.stdin is used more than once, the second and further use will
[35] Fix | Delete
return no lines, except perhaps for interactive use, or if it has been
[36] Fix | Delete
explicitly reset (e.g. using sys.stdin.seek(0)).
[37] Fix | Delete
[38] Fix | Delete
Empty files are opened and immediately closed; the only time their
[39] Fix | Delete
presence in the list of filenames is noticeable at all is when the
[40] Fix | Delete
last file opened is empty.
[41] Fix | Delete
[42] Fix | Delete
It is possible that the last line of a file doesn't end in a newline
[43] Fix | Delete
character; otherwise lines are returned including the trailing
[44] Fix | Delete
newline.
[45] Fix | Delete
[46] Fix | Delete
Class FileInput is the implementation; its methods filename(),
[47] Fix | Delete
lineno(), fileline(), isfirstline(), isstdin(), nextfile() and close()
[48] Fix | Delete
correspond to the functions in the module. In addition it has a
[49] Fix | Delete
readline() method which returns the next input line, and a
[50] Fix | Delete
__getitem__() method which implements the sequence behavior. The
[51] Fix | Delete
sequence must be accessed in strictly sequential order; sequence
[52] Fix | Delete
access and readline() cannot be mixed.
[53] Fix | Delete
[54] Fix | Delete
Optional in-place filtering: if the keyword argument inplace=1 is
[55] Fix | Delete
passed to input() or to the FileInput constructor, the file is moved
[56] Fix | Delete
to a backup file and standard output is directed to the input file.
[57] Fix | Delete
This makes it possible to write a filter that rewrites its input file
[58] Fix | Delete
in place. If the keyword argument backup=".<some extension>" is also
[59] Fix | Delete
given, it specifies the extension for the backup file, and the backup
[60] Fix | Delete
file remains around; by default, the extension is ".bak" and it is
[61] Fix | Delete
deleted when the output file is closed. In-place filtering is
[62] Fix | Delete
disabled when standard input is read. XXX The current implementation
[63] Fix | Delete
does not work for MS-DOS 8+3 filesystems.
[64] Fix | Delete
[65] Fix | Delete
XXX Possible additions:
[66] Fix | Delete
[67] Fix | Delete
- optional getopt argument processing
[68] Fix | Delete
- isatty()
[69] Fix | Delete
- read(), read(size), even readlines()
[70] Fix | Delete
[71] Fix | Delete
"""
[72] Fix | Delete
[73] Fix | Delete
import sys, os
[74] Fix | Delete
[75] Fix | Delete
__all__ = ["input","close","nextfile","filename","lineno","filelineno",
[76] Fix | Delete
"isfirstline","isstdin","FileInput"]
[77] Fix | Delete
[78] Fix | Delete
_state = None
[79] Fix | Delete
[80] Fix | Delete
# No longer used
[81] Fix | Delete
DEFAULT_BUFSIZE = 8*1024
[82] Fix | Delete
[83] Fix | Delete
def input(files=None, inplace=0, backup="", bufsize=0,
[84] Fix | Delete
mode="r", openhook=None):
[85] Fix | Delete
"""Return an instance of the FileInput class, which can be iterated.
[86] Fix | Delete
[87] Fix | Delete
The parameters are passed to the constructor of the FileInput class.
[88] Fix | Delete
The returned instance, in addition to being an iterator,
[89] Fix | Delete
keeps global state for the functions of this module,.
[90] Fix | Delete
"""
[91] Fix | Delete
global _state
[92] Fix | Delete
if _state and _state._file:
[93] Fix | Delete
raise RuntimeError, "input() already active"
[94] Fix | Delete
_state = FileInput(files, inplace, backup, bufsize, mode, openhook)
[95] Fix | Delete
return _state
[96] Fix | Delete
[97] Fix | Delete
def close():
[98] Fix | Delete
"""Close the sequence."""
[99] Fix | Delete
global _state
[100] Fix | Delete
state = _state
[101] Fix | Delete
_state = None
[102] Fix | Delete
if state:
[103] Fix | Delete
state.close()
[104] Fix | Delete
[105] Fix | Delete
def nextfile():
[106] Fix | Delete
"""
[107] Fix | Delete
Close the current file so that the next iteration will read the first
[108] Fix | Delete
line from the next file (if any); lines not read from the file will
[109] Fix | Delete
not count towards the cumulative line count. The filename is not
[110] Fix | Delete
changed until after the first line of the next file has been read.
[111] Fix | Delete
Before the first line has been read, this function has no effect;
[112] Fix | Delete
it cannot be used to skip the first file. After the last line of the
[113] Fix | Delete
last file has been read, this function has no effect.
[114] Fix | Delete
"""
[115] Fix | Delete
if not _state:
[116] Fix | Delete
raise RuntimeError, "no active input()"
[117] Fix | Delete
return _state.nextfile()
[118] Fix | Delete
[119] Fix | Delete
def filename():
[120] Fix | Delete
"""
[121] Fix | Delete
Return the name of the file currently being read.
[122] Fix | Delete
Before the first line has been read, returns None.
[123] Fix | Delete
"""
[124] Fix | Delete
if not _state:
[125] Fix | Delete
raise RuntimeError, "no active input()"
[126] Fix | Delete
return _state.filename()
[127] Fix | Delete
[128] Fix | Delete
def lineno():
[129] Fix | Delete
"""
[130] Fix | Delete
Return the cumulative line number of the line that has just been read.
[131] Fix | Delete
Before the first line has been read, returns 0. After the last line
[132] Fix | Delete
of the last file has been read, returns the line number of that line.
[133] Fix | Delete
"""
[134] Fix | Delete
if not _state:
[135] Fix | Delete
raise RuntimeError, "no active input()"
[136] Fix | Delete
return _state.lineno()
[137] Fix | Delete
[138] Fix | Delete
def filelineno():
[139] Fix | Delete
"""
[140] Fix | Delete
Return the line number in the current file. Before the first line
[141] Fix | Delete
has been read, returns 0. After the last line of the last file has
[142] Fix | Delete
been read, returns the line number of that line within the file.
[143] Fix | Delete
"""
[144] Fix | Delete
if not _state:
[145] Fix | Delete
raise RuntimeError, "no active input()"
[146] Fix | Delete
return _state.filelineno()
[147] Fix | Delete
[148] Fix | Delete
def fileno():
[149] Fix | Delete
"""
[150] Fix | Delete
Return the file number of the current file. When no file is currently
[151] Fix | Delete
opened, returns -1.
[152] Fix | Delete
"""
[153] Fix | Delete
if not _state:
[154] Fix | Delete
raise RuntimeError, "no active input()"
[155] Fix | Delete
return _state.fileno()
[156] Fix | Delete
[157] Fix | Delete
def isfirstline():
[158] Fix | Delete
"""
[159] Fix | Delete
Returns true the line just read is the first line of its file,
[160] Fix | Delete
otherwise returns false.
[161] Fix | Delete
"""
[162] Fix | Delete
if not _state:
[163] Fix | Delete
raise RuntimeError, "no active input()"
[164] Fix | Delete
return _state.isfirstline()
[165] Fix | Delete
[166] Fix | Delete
def isstdin():
[167] Fix | Delete
"""
[168] Fix | Delete
Returns true if the last line was read from sys.stdin,
[169] Fix | Delete
otherwise returns false.
[170] Fix | Delete
"""
[171] Fix | Delete
if not _state:
[172] Fix | Delete
raise RuntimeError, "no active input()"
[173] Fix | Delete
return _state.isstdin()
[174] Fix | Delete
[175] Fix | Delete
class FileInput:
[176] Fix | Delete
"""FileInput([files[, inplace[, backup[, bufsize[, mode[, openhook]]]]]])
[177] Fix | Delete
[178] Fix | Delete
Class FileInput is the implementation of the module; its methods
[179] Fix | Delete
filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
[180] Fix | Delete
nextfile() and close() correspond to the functions of the same name
[181] Fix | Delete
in the module.
[182] Fix | Delete
In addition it has a readline() method which returns the next
[183] Fix | Delete
input line, and a __getitem__() method which implements the
[184] Fix | Delete
sequence behavior. The sequence must be accessed in strictly
[185] Fix | Delete
sequential order; random access and readline() cannot be mixed.
[186] Fix | Delete
"""
[187] Fix | Delete
[188] Fix | Delete
def __init__(self, files=None, inplace=0, backup="", bufsize=0,
[189] Fix | Delete
mode="r", openhook=None):
[190] Fix | Delete
if isinstance(files, basestring):
[191] Fix | Delete
files = (files,)
[192] Fix | Delete
else:
[193] Fix | Delete
if files is None:
[194] Fix | Delete
files = sys.argv[1:]
[195] Fix | Delete
if not files:
[196] Fix | Delete
files = ('-',)
[197] Fix | Delete
else:
[198] Fix | Delete
files = tuple(files)
[199] Fix | Delete
self._files = files
[200] Fix | Delete
self._inplace = inplace
[201] Fix | Delete
self._backup = backup
[202] Fix | Delete
self._savestdout = None
[203] Fix | Delete
self._output = None
[204] Fix | Delete
self._filename = None
[205] Fix | Delete
self._startlineno = 0
[206] Fix | Delete
self._filelineno = 0
[207] Fix | Delete
self._file = None
[208] Fix | Delete
self._isstdin = False
[209] Fix | Delete
self._backupfilename = None
[210] Fix | Delete
# restrict mode argument to reading modes
[211] Fix | Delete
if mode not in ('r', 'rU', 'U', 'rb'):
[212] Fix | Delete
raise ValueError("FileInput opening mode must be one of "
[213] Fix | Delete
"'r', 'rU', 'U' and 'rb'")
[214] Fix | Delete
self._mode = mode
[215] Fix | Delete
if inplace and openhook:
[216] Fix | Delete
raise ValueError("FileInput cannot use an opening hook in inplace mode")
[217] Fix | Delete
elif openhook and not hasattr(openhook, '__call__'):
[218] Fix | Delete
raise ValueError("FileInput openhook must be callable")
[219] Fix | Delete
self._openhook = openhook
[220] Fix | Delete
[221] Fix | Delete
def __del__(self):
[222] Fix | Delete
self.close()
[223] Fix | Delete
[224] Fix | Delete
def close(self):
[225] Fix | Delete
try:
[226] Fix | Delete
self.nextfile()
[227] Fix | Delete
finally:
[228] Fix | Delete
self._files = ()
[229] Fix | Delete
[230] Fix | Delete
def __iter__(self):
[231] Fix | Delete
return self
[232] Fix | Delete
[233] Fix | Delete
def next(self):
[234] Fix | Delete
while 1:
[235] Fix | Delete
line = self._readline()
[236] Fix | Delete
if line:
[237] Fix | Delete
self._filelineno += 1
[238] Fix | Delete
return line
[239] Fix | Delete
if not self._file:
[240] Fix | Delete
raise StopIteration
[241] Fix | Delete
self.nextfile()
[242] Fix | Delete
# repeat with next file
[243] Fix | Delete
[244] Fix | Delete
def __getitem__(self, i):
[245] Fix | Delete
if i != self.lineno():
[246] Fix | Delete
raise RuntimeError, "accessing lines out of order"
[247] Fix | Delete
try:
[248] Fix | Delete
return self.next()
[249] Fix | Delete
except StopIteration:
[250] Fix | Delete
raise IndexError, "end of input reached"
[251] Fix | Delete
[252] Fix | Delete
def nextfile(self):
[253] Fix | Delete
savestdout = self._savestdout
[254] Fix | Delete
self._savestdout = 0
[255] Fix | Delete
if savestdout:
[256] Fix | Delete
sys.stdout = savestdout
[257] Fix | Delete
[258] Fix | Delete
output = self._output
[259] Fix | Delete
self._output = 0
[260] Fix | Delete
try:
[261] Fix | Delete
if output:
[262] Fix | Delete
output.close()
[263] Fix | Delete
finally:
[264] Fix | Delete
file = self._file
[265] Fix | Delete
self._file = None
[266] Fix | Delete
try:
[267] Fix | Delete
del self._readline # restore FileInput._readline
[268] Fix | Delete
except AttributeError:
[269] Fix | Delete
pass
[270] Fix | Delete
try:
[271] Fix | Delete
if file and not self._isstdin:
[272] Fix | Delete
file.close()
[273] Fix | Delete
finally:
[274] Fix | Delete
backupfilename = self._backupfilename
[275] Fix | Delete
self._backupfilename = 0
[276] Fix | Delete
if backupfilename and not self._backup:
[277] Fix | Delete
try: os.unlink(backupfilename)
[278] Fix | Delete
except OSError: pass
[279] Fix | Delete
[280] Fix | Delete
self._isstdin = False
[281] Fix | Delete
[282] Fix | Delete
def readline(self):
[283] Fix | Delete
while 1:
[284] Fix | Delete
line = self._readline()
[285] Fix | Delete
if line:
[286] Fix | Delete
self._filelineno += 1
[287] Fix | Delete
return line
[288] Fix | Delete
if not self._file:
[289] Fix | Delete
return line
[290] Fix | Delete
self.nextfile()
[291] Fix | Delete
# repeat with next file
[292] Fix | Delete
[293] Fix | Delete
def _readline(self):
[294] Fix | Delete
if not self._files:
[295] Fix | Delete
return ""
[296] Fix | Delete
self._filename = self._files[0]
[297] Fix | Delete
self._files = self._files[1:]
[298] Fix | Delete
self._startlineno = self.lineno()
[299] Fix | Delete
self._filelineno = 0
[300] Fix | Delete
self._file = None
[301] Fix | Delete
self._isstdin = False
[302] Fix | Delete
self._backupfilename = 0
[303] Fix | Delete
if self._filename == '-':
[304] Fix | Delete
self._filename = '<stdin>'
[305] Fix | Delete
self._file = sys.stdin
[306] Fix | Delete
self._isstdin = True
[307] Fix | Delete
else:
[308] Fix | Delete
if self._inplace:
[309] Fix | Delete
self._backupfilename = (
[310] Fix | Delete
self._filename + (self._backup or os.extsep+"bak"))
[311] Fix | Delete
try: os.unlink(self._backupfilename)
[312] Fix | Delete
except os.error: pass
[313] Fix | Delete
# The next few lines may raise IOError
[314] Fix | Delete
os.rename(self._filename, self._backupfilename)
[315] Fix | Delete
self._file = open(self._backupfilename, self._mode)
[316] Fix | Delete
try:
[317] Fix | Delete
perm = os.fstat(self._file.fileno()).st_mode
[318] Fix | Delete
except OSError:
[319] Fix | Delete
self._output = open(self._filename, "w")
[320] Fix | Delete
else:
[321] Fix | Delete
fd = os.open(self._filename,
[322] Fix | Delete
os.O_CREAT | os.O_WRONLY | os.O_TRUNC,
[323] Fix | Delete
perm)
[324] Fix | Delete
self._output = os.fdopen(fd, "w")
[325] Fix | Delete
try:
[326] Fix | Delete
if hasattr(os, 'chmod'):
[327] Fix | Delete
os.chmod(self._filename, perm)
[328] Fix | Delete
except OSError:
[329] Fix | Delete
pass
[330] Fix | Delete
self._savestdout = sys.stdout
[331] Fix | Delete
sys.stdout = self._output
[332] Fix | Delete
else:
[333] Fix | Delete
# This may raise IOError
[334] Fix | Delete
if self._openhook:
[335] Fix | Delete
self._file = self._openhook(self._filename, self._mode)
[336] Fix | Delete
else:
[337] Fix | Delete
self._file = open(self._filename, self._mode)
[338] Fix | Delete
[339] Fix | Delete
self._readline = self._file.readline # hide FileInput._readline
[340] Fix | Delete
return self._readline()
[341] Fix | Delete
[342] Fix | Delete
def filename(self):
[343] Fix | Delete
return self._filename
[344] Fix | Delete
[345] Fix | Delete
def lineno(self):
[346] Fix | Delete
return self._startlineno + self._filelineno
[347] Fix | Delete
[348] Fix | Delete
def filelineno(self):
[349] Fix | Delete
return self._filelineno
[350] Fix | Delete
[351] Fix | Delete
def fileno(self):
[352] Fix | Delete
if self._file:
[353] Fix | Delete
try:
[354] Fix | Delete
return self._file.fileno()
[355] Fix | Delete
except ValueError:
[356] Fix | Delete
return -1
[357] Fix | Delete
else:
[358] Fix | Delete
return -1
[359] Fix | Delete
[360] Fix | Delete
def isfirstline(self):
[361] Fix | Delete
return self._filelineno == 1
[362] Fix | Delete
[363] Fix | Delete
def isstdin(self):
[364] Fix | Delete
return self._isstdin
[365] Fix | Delete
[366] Fix | Delete
[367] Fix | Delete
def hook_compressed(filename, mode):
[368] Fix | Delete
ext = os.path.splitext(filename)[1]
[369] Fix | Delete
if ext == '.gz':
[370] Fix | Delete
import gzip
[371] Fix | Delete
return gzip.open(filename, mode)
[372] Fix | Delete
elif ext == '.bz2':
[373] Fix | Delete
import bz2
[374] Fix | Delete
return bz2.BZ2File(filename, mode)
[375] Fix | Delete
else:
[376] Fix | Delete
return open(filename, mode)
[377] Fix | Delete
[378] Fix | Delete
[379] Fix | Delete
def hook_encoded(encoding):
[380] Fix | Delete
import io
[381] Fix | Delete
def openhook(filename, mode):
[382] Fix | Delete
mode = mode.replace('U', '').replace('b', '') or 'r'
[383] Fix | Delete
return io.open(filename, mode, encoding=encoding, newline='')
[384] Fix | Delete
return openhook
[385] Fix | Delete
[386] Fix | Delete
[387] Fix | Delete
def _test():
[388] Fix | Delete
import getopt
[389] Fix | Delete
inplace = 0
[390] Fix | Delete
backup = 0
[391] Fix | Delete
opts, args = getopt.getopt(sys.argv[1:], "ib:")
[392] Fix | Delete
for o, a in opts:
[393] Fix | Delete
if o == '-i': inplace = 1
[394] Fix | Delete
if o == '-b': backup = a
[395] Fix | Delete
for line in input(args, inplace=inplace, backup=backup):
[396] Fix | Delete
if line[-1:] == '\n': line = line[:-1]
[397] Fix | Delete
if line[-1:] == '\r': line = line[:-1]
[398] Fix | Delete
print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
[399] Fix | Delete
isfirstline() and "*" or "", line)
[400] Fix | Delete
print "%d: %s[%d]" % (lineno(), filename(), filelineno())
[401] Fix | Delete
[402] Fix | Delete
if __name__ == '__main__':
[403] Fix | Delete
_test()
[404] Fix | Delete
[405] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function