Python fileinput 模块,input() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用fileinput.input()。
def read_pdns_conf(path='/etc/powerdns/pdns.conf'):
global api_host
global api_port
global api_key
try:
for line in fileinput.input([path]):
if line[0] == '#' or line[0] == '\n':
continue
try:
(key, val) = line.rstrip().split('=')
if key == 'webserver-address':
api_host = val
elif key == 'webserver-port':
api_port = int(val)
elif key == 'experimental-api-key':
api_key = val
except:
pass
except:
raise
def replacestrs(filename):
"replace a certain type of string occurances in all files in a directory"
files = glob.glob(filename)
#print 'files in files:', files
stext = '-d0'
rtext = '-r0'
for line in fileinput.input(files,inplace=1):
lineno = 0
lineno = string.find(line, stext)
if lineno >0:
line =line.replace(stext, rtext)
sys.stdout.write(line)
def set_robotframework_vars(cls, odlusername="admin", odlpassword="admin"):
"""Set credentials in csit/variables/Variables.robot.
Returns:
True if credentials are set.
False otherwise.
"""
try:
for line in fileinput.input(cls.odl_variables_file,
inplace=True):
print(re.sub("@{AUTH}.*",
"@{{AUTH}} {} {}".format(
odlusername, odlpassword),
line.rstrip()))
return True
except Exception: # pylint: disable=broad-except
cls.__logger.exception("Cannot set ODL creds:")
return False
def linkedin_search():
linkedin_login()
time.sleep(2)
x = driver.find_element_by_class_name('type-ahead-input')
search = x.find_element_by_tag_name('input')
search.send_keys('harvard')
search.send_keys(Keys.ENTER)
time.sleep(8)
new_url = (driver.current_url).replace('index', 'schools')
new_url = new_url.replace('GLOBAL_SEARCH_HEADER', 'SWITCH_SEARCH_VERTICAL')
driver.get(new_url)
time.sleep(5)
driver.find_element_by_css_selector('#ember1790').click()
time.sleep(5)
x = driver.find_element_by_class_name('company-actions-bar')
x.find_element_by_tag_name('a').click()
time.sleep(5)
start_year = driver.find_element_by_id('alumni-search-year-start')
end_year = driver.find_element_by_id('alumni-search-year-end')
start_year.send_keys('2014')
start_year.send_keys(Keys.ENTER)
time.sleep(3)
list_of_people = driver.find_elements_by_class_name('org-alumni-profiles-module__profiles-list-item')
for i in list_of_people:
print(i.text)
def start_cracking_engine(self):
print "[+] Loading Zipfile... ",
fileload=zipfile.ZipFile(self.filename)
print "OK"
if self.dictionery:
print "[+] Using Dictonery Option.... OK"
print "[+] Loading Dictonery File... OK"
print "[+] Brute Force Started ..."
for i in fileinput.input(self.dictionery):
pwd=i.strip('\n')
self.extracting_engine(fileload,pwd)
if self.crunch:
print "[+] Connection Stablished as Pipe... OK"
print "[+] Brute Force Started ..."
for i in sys.stdin:
pwd=i.strip('\n')
self.extracting_engine(fileload,pwd)
self.show_info_message()
return
def lastvm(name, delete=False):
configdir = "%s/.kcli/" % os.environ.get('HOME')
vmfile = "%s/vm" % configdir
if not os.path.exists(configdir):
os.mkdir(configdir)
if delete:
if not os.path.exists(vmfile):
return
else:
os.system("sed -i '/%s/d' %s/vm" % (name, configdir))
return
if not os.path.exists(vmfile) or os.stat(vmfile).st_size == 0:
with open(vmfile, 'w') as f:
f.write(name)
return
firstline = True
for line in fileinput.input(vmfile, inplace=True):
line = "%s\n%s" % (name, line) if firstline else line
print line,
firstline = False
def _set_x0(self, x0):
if x0 == str(x0):
x0 = eval(x0)
self.x0 = array(x0) # should not have column or row, is just 1-D
if self.x0.ndim == 2:
if self.opts.eval('verbose') >= 0:
_print_warning('input x0 should be a list or 1-D array, trying to flatten ' +
str(self.x0.shape) + '-array')
if self.x0.shape[0] == 1:
self.x0 = self.x0[0]
elif self.x0.shape[1] == 1:
self.x0 = array([x[0] for x in self.x0])
if self.x0.ndim != 1:
raise _Error('x0 must be 1-D array')
if len(self.x0) <= 1:
raise _Error('optimization in 1-D is not supported (code was never tested)')
self.x0.resize(self.x0.shape[0]) # 1-D array, not really necessary?!
# ____________________________________________________________
# ____________________________________________________________
def __call__(self, x, inverse=False): # function when calling an object
"""Rotates the input array `x` with a fixed rotation matrix
(``self.dicMatrices['str(len(x))']``)
"""
x = np.array(x, copy=False)
N = x.shape[0] # can be an array or matrix, TODO: accept also a list of arrays?
if str(N) not in self.dicMatrices: # create new N-basis for once and all
rstate = np.random.get_state()
np.random.seed(self.seed) if self.seed else np.random.seed()
B = np.random.randn(N, N)
for i in range(N):
for j in range(0, i):
B[i] -= np.dot(B[i], B[j]) * B[j]
B[i] /= sum(B[i]**2)**0.5
self.dicMatrices[str(N)] = B
np.random.set_state(rstate)
if inverse:
return np.dot(self.dicMatrices[str(N)].T, x) # compute rotation
else:
return np.dot(self.dicMatrices[str(N)], x) # compute rotation
# Use rotate(x) to rotate x
def main():
"""
Parse arguments and start the program
"""
# Iterate over all lines in all files
# listed in sys.argv[1:]
# or stdin if no args given.
try:
for line in fileinput.input():
# Look for an INSERT statement and parse it.
if is_insert(line):
values = get_values(line)
if values_sanity_check(values):
parse_values(values, sys.stdout)
except KeyboardInterrupt:
sys.exit(0)
def _create_combined_bundle_file(self):
leap_ca_bundle = ca_bundle.where()
if self._ca_cert_path == leap_ca_bundle:
return self._ca_cert_path # don't merge file with itself
elif not self._ca_cert_path:
return leap_ca_bundle
tmp_file = tempfile.NamedTemporaryFile(delete=False)
with open(tmp_file.name, 'w') as fout:
fin = fileinput.input(files=(leap_ca_bundle, self._ca_cert_path))
for line in fin:
fout.write(line)
fin.close()
return tmp_file.name
def __init__(self):
super(SessionStdIn, self).__init__()
for current_string in fileinput.input("-"):
read_lines = 0
current_line = [x.strip() for x in current_string.split(options.cfg.input_separator)]
if current_line:
if options.cfg.file_has_headers and not self.header:
self.header = current_line
else:
if read_lines >= options.cfg.skip_lines:
query_string = current_line.pop(options.cfg.query_column_number - 1)
new_query = self.query_type(query_string, self)
self.query_list.append(new_query)
self.max_number_of_input_columns = max(len(current_line), self.max_number_of_input_columns)
read_lines += 1
logger.info("Reading standard input ({} {})".format(len(self.query_list), "query" if len(self.query_list) == 1 else "queries"))
if options.cfg.skip_lines:
logger.info("Skipping first %s %s." % (options.cfg.skip_lines, "query" if options.cfg.skip_lines == 1 else "queries"))
def _set_x0(self, x0):
if x0 == str(x0):
x0 = eval(x0)
self.x0 = array(x0) # should not have column or row, is just 1-D
if self.x0.ndim == 2:
if self.opts.eval('verbose') >= 0:
_print_warning('input x0 should be a list or 1-D array, trying to flatten ' +
str(self.x0.shape) + '-array')
if self.x0.shape[0] == 1:
self.x0 = self.x0[0]
elif self.x0.shape[1] == 1:
self.x0 = array([x[0] for x in self.x0])
if self.x0.ndim != 1:
raise _Error('x0 must be 1-D array')
if len(self.x0) <= 1:
raise _Error('optimization in 1-D is not supported (code was never tested)')
self.x0.resize(self.x0.shape[0]) # 1-D array, not really necessary?!
# ____________________________________________________________
# ____________________________________________________________
def __call__(self, x, inverse=False): # function when calling an object
"""Rotates the input array `x` with a fixed rotation matrix
(``self.dicMatrices['str(len(x))']``)
"""
x = np.array(x, copy=False)
N = x.shape[0] # can be an array or matrix, TODO: accept also a list of arrays?
if str(N) not in self.dicMatrices: # create new N-basis for once and all
rstate = np.random.get_state()
np.random.seed(self.seed) if self.seed else np.random.seed()
B = np.random.randn(N, N)
for i in range(N):
for j in range(0, i):
B[i] -= np.dot(B[i], B[j]) * B[j]
B[i] /= sum(B[i]**2)**0.5
self.dicMatrices[str(N)] = B
np.random.set_state(rstate)
if inverse:
return np.dot(self.dicMatrices[str(N)].T, x) # compute rotation
else:
return np.dot(self.dicMatrices[str(N)], x) # compute rotation
# Use rotate(x) to rotate x
def REPIC(obToPrint):
'''REPIC stands for Read, Evaluate, Print In Comment. Call this function with an object obToPrint and it will rewrite the current file with the output in the comment in a line after this was called.'''
cf = inspect.currentframe()
callingFile = inspect.getfile(cf.f_back)
callingLine = cf.f_back.f_lineno
# print 'Line I am calling REPIC from:', callingLine
for line in fileinput.input(callingFile, inplace=1):
if callingLine == fileinput.filelineno():
# Make results, but get rid of newlines in output since that will break the comment:
resultString = '#OUTPUT: ' + str(obToPrint).replace('\n','\\n') +'\n'
writeIndex = line.rfind('\n')
# Watch out for last line without newlines, there the end is just the line length.
if '\n' not in line:
writeIndex = len(line)
# Replace old output and/or any comments:
if '#' in line:
writeIndex = line.rfind('#')
output = line[0:writeIndex] + resultString
else:
output = line # If no REPIC, then don't change the line.
sys.stdout.write(output)
def patch_step(self):
"""Patch Boost source code before building."""
super(EB_Boost, self).patch_step()
# TIME_UTC is also defined in recent glibc versions, so we need to rename it for old Boost versions (<= 1.49)
glibc_version = get_glibc_version()
old_glibc = glibc_version is not UNKNOWN and LooseVersion(glibc_version) > LooseVersion("2.15")
if old_glibc and LooseVersion(self.version) <= LooseVersion("1.49.0"):
self.log.info("Patching because the glibc version is too new")
files_to_patch = ["boost/thread/xtime.hpp"] + glob.glob("libs/interprocess/test/*.hpp")
files_to_patch += glob.glob("libs/spirit/classic/test/*.cpp") + glob.glob("libs/spirit/classic/test/*.inl")
for patchfile in files_to_patch:
try:
for line in fileinput.input("%s" % patchfile, inplace=1, backup='.orig'):
line = re.sub(r"TIME_UTC", r"TIME_UTC_", line)
sys.stdout.write(line)
except IOError, err:
raise EasyBuildError("Failed to patch %s: %s", patchfile, err)
def post_install_step(self):
"""Custom post install step for IMPI, fix broken env scripts after moving installed files."""
super(EB_impi, self).post_install_step()
impiver = LooseVersion(self.version)
if impiver == LooseVersion('4.1.1.036') or impiver >= LooseVersion('5.0.1.035'):
if impiver >= LooseVersion('2018.0.128'):
script_paths = [os.path.join('intel64', 'bin')]
else:
script_paths = [os.path.join('intel64', 'bin'), os.path.join('mic', 'bin')]
# fix broken env scripts after the move
for script in [os.path.join(script_path,'mpivars.csh') for script_path in script_paths]:
for line in fileinput.input(os.path.join(self.installdir, script), inplace=1, backup='.orig.easybuild'):
line = re.sub(r"^setenv I_MPI_ROOT.*", "setenv I_MPI_ROOT %s" % self.installdir, line)
sys.stdout.write(line)
for script in [os.path.join(script_path,'mpivars.sh') for script_path in script_paths]:
for line in fileinput.input(os.path.join(self.installdir, script), inplace=1, backup='.orig.easybuild'):
line = re.sub(r"^I_MPI_ROOT=.*", "I_MPI_ROOT=%s; export I_MPI_ROOT" % self.installdir, line)
sys.stdout.write(line)
def patch_step(self):
"""Patch Boost source code before building."""
super(boostcray, self).patch_step()
# TIME_UTC is also defined in recent glibc versions, so we need to rename it for old Boost versions (<= 1.47)
glibc_version = get_glibc_version()
old_glibc = glibc_version is not UNKNOWN and LooseVersion(glibc_version) > LooseVersion("2.15")
if old_glibc and LooseVersion(self.version) <= LooseVersion("1.47.0"):
self.log.info("Patching because the glibc version is too new")
files_to_patch = ["boost/thread/xtime.hpp"] + glob.glob("libs/interprocess/test/*.hpp")
files_to_patch += glob.glob("libs/spirit/classic/test/*.cpp") + glob.glob("libs/spirit/classic/test/*.inl")
for patchfile in files_to_patch:
try:
for line in fileinput.input("%s" % patchfile, inplace=1, backup='.orig'):
line = re.sub(r"TIME_UTC", r"TIME_UTC_", line)
sys.stdout.write(line)
except IOError, err:
raise EasyBuildError("Failed to patch %s: %s", patchfile, err)
def patch_step(self):
"""Patch Boost source code before building."""
super(EB_Boost, self).patch_step()
# TIME_UTC is also defined in recent glibc versions, so we need to rename it for old Boost versions (<= 1.47)
glibc_version = get_glibc_version()
old_glibc = glibc_version is not UNKNOWN and LooseVersion(glibc_version) > LooseVersion("2.15")
if old_glibc and LooseVersion(self.version) <= LooseVersion("1.47.0"):
self.log.info("Patching because the glibc version is too new")
files_to_patch = ["boost/thread/xtime.hpp"] + glob.glob("libs/interprocess/test/*.hpp")
files_to_patch += glob.glob("libs/spirit/classic/test/*.cpp") + glob.glob("libs/spirit/classic/test/*.inl")
for patchfile in files_to_patch:
try:
for line in fileinput.input("%s" % patchfile, inplace=1, backup='.orig'):
line = re.sub(r"TIME_UTC", r"TIME_UTC_", line)
sys.stdout.write(line)
except IOError, err:
raise EasyBuildError("Failed to patch %s: %s", patchfile, err)
def _set_x0(self, x0):
if (isinstance(x0, str) and x0 == str(x0)):
x0 = eval(x0)
self.x0 = array(x0) # should not have column or row, is just 1-D
if self.x0.ndim == 2:
if self.opts.eval('verbose') >= 0:
_print_warning('input x0 should be a list or 1-D array, trying to flatten ' +
str(self.x0.shape) + '-array')
if self.x0.shape[0] == 1:
self.x0 = self.x0[0]
elif self.x0.shape[1] == 1:
self.x0 = array([x[0] for x in self.x0])
if self.x0.ndim != 1:
raise _Error('x0 must be 1-D array')
if len(self.x0) <= 1:
raise _Error('optimization in 1-D is not supported (code was never tested)')
self.x0.resize(self.x0.shape[0]) # 1-D array, not really necessary?!
# ____________________________________________________________
# ____________________________________________________________
def __call__(self, x, inverse=False): # function when calling an object
"""Rotates the input array `x` with a fixed rotation matrix
(``self.dicMatrices['str(len(x))']``)
"""
x = np.array(x, copy=False)
N = x.shape[0] # can be an array or matrix, TODO: accept also a list of arrays?
if str(N) not in self.dicMatrices: # create new N-basis for once and all
rstate = np.random.get_state()
np.random.seed(self.seed) if self.seed else np.random.seed()
B = np.random.randn(N, N)
for i in xrange(N):
for j in xrange(0, i):
B[i] -= np.dot(B[i], B[j]) * B[j]
B[i] /= sum(B[i]**2)**0.5
self.dicMatrices[str(N)] = B
np.random.set_state(rstate)
if inverse:
return np.dot(self.dicMatrices[str(N)].T, x) # compute rotation
else:
return np.dot(self.dicMatrices[str(N)], x) # compute rotation
# Use rotate(x) to rotate x
def print_help():
print "Usage:\n"
print "\tpython SameFileFinder.python [arg0] [arg1]\n"
print "Args:\n"
print "\t[arg0] - Target Directory of files should be scan"
print "\t[arg1] - Doc Suffix of files should be scan, eg"
print "\t\t .m - Object-C file"
print "\t\t .swift - Swift file"
print "\t\t .java - Java file\n"
print "\t--max-distance=[input] - max hamming distance to keep, default is 20"
print "\t--min-linecount=[input] - for function scan, the function would be ignore if the total line count of the function less than min-linecount"
print "\t--functions - Use Functions as code scan standard"
print "\t Attention: The \"--functions\" support just Object-C and Java now"
print "\t--detail - Show the detail of process\n"
print "\t--output=[intput] - Customize the output file, default is \"out.txt\""
################ End Util Funcs ################
def show_warning():
print("""************** WARNING *********************8
backport3to2.py performs an in-place modification of the SuperBook
project so that it works in Python 2.7. Hence, it will NOT WORK
correctly for Python 3.4 anymore. Please note that this is one-way
conversion and cannot be reversed.
Please confirm by pressing 'y' or 'Y' if you are sure that you would
like to continue with this conversion to Python 2.7. Press any other
key to abort: """, end="")
real_raw_input = vars(__builtins__).get('raw_input', input)
choice = real_raw_input().lower()
if choice != 'y':
sys.exit(-1)
if 'raw_input' not in vars(__builtins__):
print("""\nLooks like your are already on Python 3. This script
is for Python 2 users. Are you sure you want to continue?
(Y/N): """, end="")
choice = real_raw_input().lower()
if choice != 'y':
sys.exit(-1)
return
def main(argv):
state = 0
for line in fileinput.input():
line = line.strip()
if not line or line.startswith('#'):
if state == 1:
state = 2
print ('}\n')
print (line)
continue
if state == 0:
print ('\nglyphname2unicode = {')
state = 1
(name,x) = line.split(';')
codes = x.split(' ')
print (' %r: u\'%s\',' % (name, ''.join( '\\u%s' % code for code in codes )))
def main(argv):
import getopt, fileinput
def usage():
print ('usage: %s [-c codec] file ...' % argv[0])
return 100
try:
(opts, args) = getopt.getopt(argv[1:], 'c')
except getopt.GetoptError:
return usage()
if not args: return usage()
codec = 'utf-8'
for (k, v) in opts:
if k == '-c': codec = v
for line in fileinput.input(args):
line = latin2ascii(unicode(line, codec, 'ignore'))
sys.stdout.write(line.encode('ascii', 'replace'))
return
def run(self, stdin):
'''
Run the hooks as specified in the given configuration file.
Report messages and status.
'''
hooks = self.hooks
permit = True
# Read in each ref that the user is trying to update
for line in fileinput.input(stdin):
old_sha, new_sha, branch = line.strip().split(' ')
for hook in hooks:
status, messages = hook.check(branch, old_sha, new_sha)
for message in messages:
print "[%s @ %s]: %s" % (branch, message['at'][:7], message['text'])
permit = permit and status
if not permit:
sys.exit(1)
sys.exit(0)
def parse_spec(file):
classes = {}
cur = None
for line in fileinput.input(file):
if line.strip().startswith('#'):
continue
mo = rx_init.search(line)
if mo is None:
if cur is None:
# a normal entry
try:
name, args = line.split(':')
except ValueError:
continue
classes[name] = NodeInfo(name, args)
cur = None
else:
# some code for the __init__ method
cur.init.append(line)
else:
# some extra code for a Node's __init__ method
name = mo.group(1)
cur = classes[name]
return sorted(list(classes.values()), key=lambda n: n.name)
def parse_spec(file):
classes = {}
cur = None
for line in fileinput.input(file):
if line.strip().startswith('#'):
continue
mo = rx_init.search(line)
if mo is None:
if cur is None:
# a normal entry
try:
name, args = line.split(':')
except ValueError:
continue
classes[name] = NodeInfo(name, args)
cur = None
else:
# some code for the __init__ method
cur.init.append(line)
else:
# some extra code for a Node's __init__ method
name = mo.group(1)
cur = classes[name]
return sorted(classes.values(), key=lambda n: n.name)
def train(solver_prototxt_filename, init, init_type):
for line in fileinput.input('train_net.sh', inplace=True):
if '-solver' in line:
tmp = line.split('-solver')
if init==None:
print tmp[0]+" -solver "+ solver_prototxt_filename
elif init_type == 'fin':
print tmp[0]+" -solver "+ solver_prototxt_filename +" -weights " + init # .caffemodel file requiered for finetuning
elif init_type == 'res':
print tmp[0]+" -solver "+ solver_prototxt_filename +" -snapshot " + init # .solverstate file requiered for resuming training
else:
raise ValueError("No specific init_type defined for pre-trained network "+init)
else:
print line,
os.system("chmod +x train_net.sh")
os.system('./train_net.sh')
def connection_db(self,db_name):
'''
?????
:param db_name: ??????
:return: ???????
'''
##????
conf = {}
for line in fileinput.input(self.MYSQL_CONF):
lines = line.replace(' ', '').replace('\n', '').replace('\r', '').split("=")
conf[lines[0]] = lines[1]
try:
conn = MySQLdb.connect(host=conf["IP"], port=int(conf["PORT"]), user=conf["USER_NAME"], passwd=conf["PWD"],
db=db_name, charset='utf8')
return conn
except Exception,e:
print "???????!Error:",e
##?????
def replaceInFile(_fil, patternToFind='', strToReplace=None, byOccurStr=''):
"""
In file '_fil', on lines matching 'patternToFind' : string 'strToReplace' will be replaced by 'byOccurStr'
:param str patternToFind: lines matching the patternToFind will be selected for change. regex compliant
if empty string, all lines will be selected
:param str strToReplace: the string to be modified on the line selected . regex compliant.
strToReplace=None means strToReplace = patternToFind
:param str byOccurStr: string 'strToReplace' will be replaced by string 'byOccur'
"""
if strToReplace is None:
strToReplace = patternToFind
# fileinput allows to replace "in-place" directly into the file
for lin in fileinput.input(_fil, inplace=1):
if re.search(patternToFind, lin):
lin = re.sub(strToReplace, byOccurStr, lin.rstrip())
print(lin)
def replaceInFile(_fil, patternToFind='', strToReplace=None, byOccurStr=''):
"""
In file '_fil', on lines matching 'patternToFind' : string 'strToReplace' will be replaced by 'byOccurStr'
:param str patternToFind: lines matching the patternToFind will be selected for change. regex compliant
if empty string, all lines will be selected
:param str strToReplace: the string to be modified on the line selected . regex compliant.
strToReplace=None means strToReplace = patternToFind
:param str byOccurStr: string 'strToReplace' will be replaced by string 'byOccur'
"""
if strToReplace is None:
strToReplace = patternToFind
# fileinput allows to replace "in-place" directly into the file
for lin in fileinput.input(_fil, inplace=1):
if re.search(patternToFind, lin):
lin = re.sub(strToReplace, byOccurStr, lin.rstrip())
print(lin)
def draw_loop():
"""
Draw the graph in a loop
"""
global G
plt.ion()
# mng = plt.get_current_fig_manager()
# mng.resize(*mng.window.maxsize())
plt.draw()
for line in fileinput.input():
if output(line):
plt.clf()
nx.draw(G)
plt.draw()
def build_kernel(self, jobs):
kernel_config_path = os.path.join(self.__kernel_source_dir__, '.config')
if 'CONFIG_DEBUG_INFO=y' in open(self.base_config_path).read():
print("DEBUG_INFO correctly present")
elif 'CONFIG_DEBUG_INFO=n' in open(self.base_config_path).read():
print("changing DEBUG_INFO to yes")
for line in fileinput.input(self.base_config_path, inplace=1):
print(line.replace("CONFIG_DEBUG_INFO=n", "CONFIG_DEBUG_INFO=y"))
else:
print("Adding DEBUG_INFO for getting kernel debug symbols")
for line in fileinput.input(self.base_config_path, inplace=1):
print(line.replace("# CONFIG_DEBUG_INFO is not set", "CONFIG_DEBUG_INFO=y"))
shutil.copyfile(self.base_config_path, kernel_config_path)
# olddefconfig default everything that is new from the configuration file
_command(['make', 'olddefconfig'], self.__kernel_source_dir__)
# copy the olddefconfig generated config file back,
# so that we don't trigger a config restart when kpatch-build runs
shutil.copyfile(kernel_config_path, self.base_config_path)
_command(['make', '-j', str(jobs)], self.__kernel_source_dir__)
_command(['make', 'modules'], self.__kernel_source_dir__)
def replace_line(f, start_exp, to_replace):
for line in fileinput.input(f, inplace=1):
if line.startswith(start_exp):
line = to_replace
sys.stdout.write(line)
def parseIplInst( files ):
class INSTline:
def __init__(self):
self.ModelID = -1
self.ModelName = ""
self.Interior = 0
self.Pos = ()
self.Scale = ()
self.Rot = ()
parse = False
instlist = {}
for line in fileinput.input( files ):
line = line.strip().split('#', 1)[0]
if line == "end":
parse = False
if parse == True:
tokens = line.split(", ")
modelId = int(tokens[0])
instlist.setdefault( modelId, [])
inst = INSTline()
inst.ModelID = modelId
inst.ModelName = tokens[1]
if len(tokens) == 12:
inst.Pos = ( float(tokens[2]), float(tokens[3]), float(tokens[4]) )
inst.Scale = ( float(tokens[5]), float(tokens[6]), float(tokens[7]) )
inst.Rot = ( float(tokens[8]), float(tokens[9]), float(tokens[10]), float(tokens[11]) )
elif len(tokens) == 13:
inst.Pos = ( float(tokens[3]), float(tokens[4]), float(tokens[5]) )
inst.Interior = int(tokens[2])
inst.Scale = ( float(tokens[6]), float(tokens[7]), float(tokens[8]) )
inst.Rot = ( float(tokens[9]), float(tokens[10]), float(tokens[11]), float(tokens[12]) )
instlist[ modelId ].append( inst )
if line == "inst":
parse = True
return instlist
def main(*args, **kwargs):
"""Program entry point"""
story_text = "\n".join(list(fileinput.input()))
story, highlights = process_story(story_text)
if story and highlights:
print("{}\t{}".format(story, highlights))
def _compress_streaming_json(self):
for line in fileinput.input():
line = line.strip()
self._process_line(line)
def _parse_binlog(self):
for line in fileinput.input():
line = line.strip()
self._process_line(line)
def input(files=None, inplace=0, backup="", bufsize=0,
mode="r", openhook=None):
"""input([files[, inplace[, backup[, mode[, openhook]]]]])
Create an instance of the FileInput class. The instance will be used
as global state for the functions of this module, and is also returned
to use during iteration. The parameters to this function will be passed
along to the constructor of the FileInput class.
"""
global _state
if _state and _state._file:
raise RuntimeError, "input() already active"
_state = FileInput(files, inplace, backup, bufsize, mode, openhook)
return _state
def nextfile():
"""
Close the current file so that the next iteration will read the first
line from the next file (if any); lines not read from the file will
not count towards the cumulative line count. The filename is not
changed until after the first line of the next file has been read.
Before the first line has been read, this function has no effect;
it cannot be used to skip the first file. After the last line of the
last file has been read, this function has no effect.
"""
if not _state:
raise RuntimeError, "no active input()"
return _state.nextfile()
def filename():
"""
Return the name of the file currently being read.
Before the first line has been read, returns None.
"""
if not _state:
raise RuntimeError, "no active input()"
return _state.filename()
def lineno():
"""
Return the cumulative line number of the line that has just been read.
Before the first line has been read, returns 0. After the last line
of the last file has been read, returns the line number of that line.
"""
if not _state:
raise RuntimeError, "no active input()"
return _state.lineno()
def filelineno():
"""
Return the line number in the current file. Before the first line
has been read, returns 0. After the last line of the last file has
been read, returns the line number of that line within the file.
"""
if not _state:
raise RuntimeError, "no active input()"
return _state.filelineno()
def isfirstline():
"""
Returns true the line just read is the first line of its file,
otherwise returns false.
"""
if not _state:
raise RuntimeError, "no active input()"
return _state.isfirstline()
def isstdin():
"""
Returns true if the last line was read from sys.stdin,
otherwise returns false.
"""
if not _state:
raise RuntimeError, "no active input()"
return _state.isstdin()
def __getitem__(self, i):
if i != self._lineno:
raise RuntimeError, "accessing lines out of order"
try:
return self.next()
except StopIteration:
raise IndexError, "end of input reached"
def _test():
import getopt
inplace = 0
backup = 0
opts, args = getopt.getopt(sys.argv[1:], "ib:")
for o, a in opts:
if o == '-i': inplace = 1
if o == '-b': backup = a
for line in input(args, inplace=inplace, backup=backup):
if line[-1:] == '\n': line = line[:-1]
if line[-1:] == '\r': line = line[:-1]
print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
isfirstline() and "*" or "", line)
print "%d: %s[%d]" % (lineno(), filename(), filelineno())
def load_data(file):
if not sys.stdin.isatty():
file = "-"
adapter = MinimalAdapter()
return yaml.safe_load(adapter(fileinput.input(file)))
def callback(arg, directory, files):
for file in files:
if fnmatch.fnmatch(file,arg):
for line in fileinput.input(os.path.abspath(os.path.join(directory, file)),inplace=1):
if re.search('.*theunderdogs.*', line): # I changed * to .* but it would probably work without this if
line = string.replace(line,'theunderdogs','the-underdogs') # old string , new string
print line,
def sort_file():
""" Sort the lines in the file named on standard input,
outputting the sorted lines on stdout.
Example call (from command line)
sort_file.py unsorted.txt > sorted.txt
"""
lines=[] # give lines variable a type of list
for line in fileinput.input(): lines.append(line.rstrip())
lines.sort()
for line in lines: print line