Python fileinput.close() Examples
The following are 30
code examples of fileinput.close().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
fileinput
, or try the search function
.
Example #1
Source File: test_fileinput.py From ironpython3 with Apache License 2.0 | 6 votes |
def test_zero_byte_files(self): t1 = t2 = t3 = t4 = None try: t1 = writeTmp(1, [""]) t2 = writeTmp(2, [""]) t3 = writeTmp(3, ["The only line there is.\n"]) t4 = writeTmp(4, [""]) fi = FileInput(files=(t1, t2, t3, t4)) line = fi.readline() self.assertEqual(line, 'The only line there is.\n') self.assertEqual(fi.lineno(), 1) self.assertEqual(fi.filelineno(), 1) self.assertEqual(fi.filename(), t3) line = fi.readline() self.assertFalse(line) self.assertEqual(fi.lineno(), 1) self.assertEqual(fi.filelineno(), 0) self.assertEqual(fi.filename(), t4) fi.close() finally: remove_tempfiles(t1, t2, t3, t4)
Example #2
Source File: ReVerb.py From Snowball with GNU General Public License v3.0 | 6 votes |
def main(): # for testing, it extracts PER-ORG relationships from a file, where each line is a sentence with # the named-entities tagged reverb = Reverb() for line in fileinput.input(): sentence = Sentence(line, "ORG", "ORG", 6, 1, 2, None) for r in sentence.relationships: pattern_tags = reverb.extract_reverb_patterns_tagged_ptb(r.between) # simple passive voice # auxiliary verb be + main verb past participle + 'by' print(r.ent1, '\t', r.ent2) print(r.sentence) print(pattern_tags) if reverb.detect_passive_voice(pattern_tags): print("Passive Voice: True") else: print("Passive Voice: False") print("\n") fileinput.close()
Example #3
Source File: libcore.py From stash with MIT License | 6 votes |
def input_stream(files=()): """ Handles input files similar to fileinput. The advantage of this function is it recovers from errors if one file is invalid and proceed with the next file """ fileinput.close() try: if not files: for line in fileinput.input(files): yield line, '', fileinput.filelineno() else: while files: thefile = files.pop(0) try: for line in fileinput.input(thefile): yield line, fileinput.filename(), fileinput.filelineno() except IOError as e: yield None, fileinput.filename(), e finally: fileinput.close()
Example #4
Source File: more.py From stash with MIT License | 6 votes |
def more(filenames, pagesize=10, clear=False, fmt='{line}'): '''Display content of filenames pagesize lines at a time (cleared if specified) with format fmt for each output line''' fileinput.close() # in case still open try: pageno = 1 if clear: clear_screen() for line in fileinput.input(filenames, openhook=fileinput.hook_encoded("utf-8")): lineno, filename, filelineno = fileinput.lineno(), fileinput.filename(), fileinput.filelineno() print(fmt.format(**locals()), end='') if pagesize and lineno % pagesize == 0: console.alert('Abort or continue', filename, 'Next page') # TODO: use less intrusive mechanism than alert pageno += 1 if clear: clear_screen() finally: fileinput.close() # --- main
Example #5
Source File: test_fileinput.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
def test_zero_byte_files(self): t1 = t2 = t3 = t4 = None try: t1 = writeTmp(1, [""]) t2 = writeTmp(2, [""]) t3 = writeTmp(3, ["The only line there is.\n"]) t4 = writeTmp(4, [""]) fi = FileInput(files=(t1, t2, t3, t4)) line = fi.readline() self.assertEqual(line, 'The only line there is.\n') self.assertEqual(fi.lineno(), 1) self.assertEqual(fi.filelineno(), 1) self.assertEqual(fi.filename(), t3) line = fi.readline() self.assertFalse(line) self.assertEqual(fi.lineno(), 1) self.assertEqual(fi.filelineno(), 0) self.assertEqual(fi.filename(), t4) fi.close() finally: remove_tempfiles(t1, t2, t3, t4)
Example #6
Source File: fileutils.py From WordOps with MIT License | 6 votes |
def searchreplace(self, fnm, sstr, rstr): """ Search replace strings in file fnm : filename sstr: search string rstr: replace string """ try: Log.debug(self, "Doing search and replace, File:{0}," "Source string:{1}, Dest String:{2}" .format(fnm, sstr, rstr)) for line in fileinput.input(fnm, inplace=True): print(line.replace(sstr, rstr), end='') fileinput.close() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to search {0} and replace {1} {2}" .format(fnm, sstr, rstr), exit=False)
Example #7
Source File: completion.py From pyimgui with BSD 3-Clause "New" or "Revised" License | 6 votes |
def output(done_count, all_count, badge_output=None): result = "%d%% (%s of %s)" % ( float(done_count)/all_count * 100, done_count, all_count ) badge_url = BASE_URL % quote(result) badge_md = BADGE_TEMPLATE % badge_url if badge_output: output_file = fileinput.input(files=(badge_output,), inplace=True) try: for line in output_file: if BADGE_RE.match(line): sys.stdout.write(badge_md + "\n") else: sys.stdout.write(line) finally: fileinput.close() click.echo("Estimated: %s" % result) click.echo("Badge: %s" % badge_md)
Example #8
Source File: batch.py From contrail-api-cli with MIT License | 6 votes |
def __call__(self, files=None): manager = CommandManager() try: for line in fileinput.input(files=files): if line[0] == '#': continue action = shlex.split(line.rstrip()) if len(action) < 1: continue cmd = manager.get(action[0]) args = action[1:] result = cmd.parse_and_call(*args) if result: printo(result) except IOError: raise CommandError("Cannot read from file: {}".format(fileinput.filename())) except CommandNotFound: raise CommandError("Command {} not found".format(action[0])) finally: fileinput.close()
Example #9
Source File: test_fileinput.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
def test_zero_byte_files(self): t1 = t2 = t3 = t4 = None try: t1 = writeTmp(1, [""]) t2 = writeTmp(2, [""]) t3 = writeTmp(3, ["The only line there is.\n"]) t4 = writeTmp(4, [""]) fi = FileInput(files=(t1, t2, t3, t4)) line = fi.readline() self.assertEqual(line, 'The only line there is.\n') self.assertEqual(fi.lineno(), 1) self.assertEqual(fi.filelineno(), 1) self.assertEqual(fi.filename(), t3) line = fi.readline() self.assertFalse(line) self.assertEqual(fi.lineno(), 1) self.assertEqual(fi.filelineno(), 0) self.assertEqual(fi.filename(), t4) fi.close() finally: remove_tempfiles(t1, t2, t3, t4)
Example #10
Source File: common.py From MARA_Framework with GNU Lesser General Public License v3.0 | 6 votes |
def writeKey(key,value): """ Function to write a key to settings.properties\n If a value exists, this will overwrite the key """ flag=0 for line in fileinput.input([rootDir +"/settings.properties"], inplace=True): if key in line: print line.replace(line, key + "=" + value) flag=1 else: print line, if flag==0: fileinput.close() f = open(rootDir + "/settings.properties","a") f.write("\n" + key + "=" + value), print "Updated config value:: %s %s" %(key,value) f.close() # Will return file names matching regex
Example #11
Source File: common.py From MARA_Framework with GNU Lesser General Public License v3.0 | 6 votes |
def getConfig(key): """ Function to retrieve a key """ value = "" for line in fileinput.input([rootDir + "/settings.properties"]): if key in line: value = line.split("=")[1] if "path" in str(key).lower(): #If its a path, verify that it exists before returning the value value = value.rstrip() if value.endswith("/"): if not os.path.exists(value.rsplit("/",1)[0]): value= "" else: if not os.path.exists(value): value="" break fileinput.close() return value.rstrip()
Example #12
Source File: cat.py From stash with MIT License | 6 votes |
def main(args): p = argparse.ArgumentParser(description=__doc__) p.add_argument("files", action="store", nargs="*", help="files to print") ns = p.parse_args(args) status = 0 fileinput.close() # in case it is not closed try: for line in fileinput.input(ns.files, openhook=fileinput.hook_encoded("utf-8")): print(filter_non_printable(line), end='') except Exception as e: print('cat: %s' % str(e)) status = 1 finally: fileinput.close() sys.exit(status)
Example #13
Source File: test_fileinput.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def writeTmp(i, lines, mode='w'): # opening in text mode is the default name = TESTFN + str(i) f = open(name, mode) for line in lines: f.write(line) f.close() return name
Example #14
Source File: test_fileinput.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_state_is_not_None(self): """Tests that fileinput.close() invokes close() on fileinput._state and sets _state=None""" instance = MockFileInput() fileinput._state = instance fileinput.close() self.assertExactlyOneInvocation(instance, "close") self.assertIsNone(fileinput._state)
Example #15
Source File: Sources.py From Resetter with GNU General Public License v3.0 | 5 votes |
def __init__(self, parent=None): super(SourceEdit, self).__init__(parent) self.resize(600, 500) self.font = QtGui.QFont() self.font.setBold(True) self.font2 = QtGui.QFont() self.font2.setBold(False) self.searchEditText = QLineEdit() self.searchEditText.setPlaceholderText("Search for repositories") palette = QtGui.QPalette() palette.setColor(QtGui.QPalette.Foreground, QtCore.Qt.red) self.label = QLabel() self.btnRemove = QPushButton() self.btDisable = QPushButton() self.btnEnable = QPushButton() self.btnClose = QPushButton() self.btnClose.setText("Close") self.btnRemove.setText("Remove entries") self.btDisable.setText("Disable entries") self.btnEnable.setText("Enable entries") self.label.setPalette(palette) self.btnRemove.clicked.connect(self.removeSelectedSources) self.btDisable.clicked.connect(self.disableSelectedSources) self.btnEnable.clicked.connect(self.enableSelectedSources) self.msg = QMessageBox() self.msg.setIcon(QMessageBox.Information) self.msg.setWindowTitle("Success") self.msg.setText("Your changes have been successfully applied") self.btnClose.clicked.connect(self.close) self.sourceslists = [] self.items = []
Example #16
Source File: Sources.py From Resetter with GNU General Public License v3.0 | 5 votes |
def disableSelectedSources(self): char = "#" for item in self.items: for line in fileinput.FileInput(self.sourceslists, inplace=1): if char not in item.text() and item.text() == line.strip()\ and item.checkState() == QtCore.Qt.Checked: disable = "{} {}".format(char, item.text()) line = line.replace(item.text(), disable) item.setText(disable) sys.stdout.write(line) fileinput.close()
Example #17
Source File: Sources.py From Resetter with GNU General Public License v3.0 | 5 votes |
def enableSelectedSources(self): for item in self.items: for line in fileinput.FileInput(self.sourceslists, inplace=1): if str(item.text()).startswith("#") and item.text() == line.strip() \ and item.checkState() == QtCore.Qt.Checked: enable = "{}".format(str(item.text())[2:]) line = line.replace(item.text(), enable) item.setText(enable) sys.stdout.write(line) fileinput.close()
Example #18
Source File: Sources.py From Resetter with GNU General Public License v3.0 | 5 votes |
def removeSelectedSources(self): item_r = list(); for item in self.items: for line in fileinput.FileInput(self.sourceslists, inplace=1): if item.text() == line.strip() \ and item.checkState() == QtCore.Qt.Checked: item_r.append(item) line = line.replace(item.text(), '') sys.stdout.write(line) fileinput.close() [self.model.removeRow(r.row()) for r in item_r]
Example #19
Source File: test_fileinput.py From ironpython3 with Apache License 2.0 | 5 votes |
def writeTmp(i, lines, mode='w'): # opening in text mode is the default name = TESTFN + str(i) f = open(name, mode) for line in lines: f.write(line) f.close() return name
Example #20
Source File: test_fileinput.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def close(self): pass
Example #21
Source File: test_fileinput.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def close(self): self.invocation_counts["close"] += 1
Example #22
Source File: test_fileinput.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_state_is_None(self): """Tests that fileinput.close() does nothing if fileinput._state is None""" fileinput._state = None fileinput.close() self.assertIsNone(fileinput._state)
Example #23
Source File: reverb.py From BREDS with GNU Lesser General Public License v3.0 | 5 votes |
def main(): reverb = Reverb() for line in fileinput.input(): tokens = word_tokenize(line.strip()) tokens_tagged = pos_tag(tokens) print(tokens_tagged) pattern_tags = reverb.extract_reverb_patterns_tagged_ptb(tokens_tagged) print(pattern_tags) if reverb.detect_passive_voice(pattern_tags): print("Passive Voice: True") else: print("Passive Voice: False") print("\n") fileinput.close()
Example #24
Source File: large-scale-evaluation-freebase.py From BREDS with GNU Lesser General Public License v3.0 | 5 votes |
def load_acronyms(data): acronyms = defaultdict(list) for line in fileinput.input(data): parts = line.split('\t') acronym = parts[0].strip() if "/" in acronym: continue expanded = parts[-1].strip() if "/" in expanded: continue acronyms[acronym].append(expanded) fileinput.close() return acronyms
Example #25
Source File: large-scale-evaluation-freebase.py From BREDS with GNU Lesser General Public License v3.0 | 5 votes |
def load_dbpedia(data, database_1, database_2): for line in fileinput.input(data): e1, rel, e2, p = line.split() e1 = e1.split('<http://dbpedia.org/resource/')[1].replace(">", "") e2 = e2.split('<http://dbpedia.org/resource/')[1].replace(">", "") e1 = re.sub("_", " ", e1) e2 = re.sub("_", " ", e2) if "(" in e1 or "(" in e2: e1 = re.sub("\(.*\)", "", e1) e2 = re.sub("\(.*\)", "", e2) # store a tuple (entity1, entity2) in a dictionary database_1[(e1.strip(), e2.strip())].append(p) # store in a dictionary per relationship: dict['ent1'] = 'ent2' database_2[e1.strip()].append(e2.strip()) else: e1 = e1.decode("utf8").strip() e2 = e2.decode("utf8").strip() # store a tuple (entity1, entity2) in a dictionary database_1[(e1, e2)].append(p) # store in a dictionary per relationship: dict['ent1'] = 'ent2' database_2[e1.strip()].append(e2.strip()) fileinput.close() return database_1, database_2
Example #26
Source File: test_fileinput.py From ironpython3 with Apache License 2.0 | 5 votes |
def close(self): self.invocation_counts["close"] += 1
Example #27
Source File: robot.py From psychsim with MIT License | 5 votes |
def WriteErrorLog(content="",root='.'): f = open(os.path.join(root,'ErrorLog.txt'),'a') print('[%s] %s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), content),file=f) f.close()
Example #28
Source File: robot.py From psychsim with MIT License | 5 votes |
def WriteLogData(content="",username=None,level=None,root='.'): """ (U) Creating logs """ filename = getFilename(username,level,extension='log',root=root) f = open(filename,'a') print('[%s] %s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), content),file=f) f.close()
Example #29
Source File: wpRobot.py From psychsim with MIT License | 5 votes |
def WriteErrorLog(content="",root='.'): f = open(os.path.join(root,'ErrorLog.txt'),'a') print >> f,'[%s] %s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), content) f.close()
Example #30
Source File: wpRobot.py From psychsim with MIT License | 5 votes |
def WriteLogData(content="",username=None,level=None,root='.'): """ (U) Creating logs """ filename = getFilename(username,level,extension='log',root=root) f = open(filename,'a') print >> f,'[%s] %s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),content) f.close()