当前位置: 首页>>代码示例>>Python>>正文


Python fileinput.close方法代码示例

本文整理汇总了Python中fileinput.close方法的典型用法代码示例。如果您正苦于以下问题:Python fileinput.close方法的具体用法?Python fileinput.close怎么用?Python fileinput.close使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在fileinput的用法示例。


在下文中一共展示了fileinput.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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() 
开发者ID:davidsbatista,项目名称:Snowball,代码行数:21,代码来源:ReVerb.py

示例2: searchreplace

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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) 
开发者ID:WordOps,项目名称:WordOps,代码行数:20,代码来源:fileutils.py

示例3: output

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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) 
开发者ID:swistakm,项目名称:pyimgui,代码行数:25,代码来源:completion.py

示例4: __call__

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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() 
开发者ID:eonpatapon,项目名称:contrail-api-cli,代码行数:22,代码来源:batch.py

示例5: test_zero_byte_files

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:25,代码来源:test_fileinput.py

示例6: main

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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) 
开发者ID:ywangd,项目名称:stash,代码行数:20,代码来源:cat.py

示例7: more

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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 
开发者ID:ywangd,项目名称:stash,代码行数:23,代码来源:more.py

示例8: input_stream

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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() 
开发者ID:ywangd,项目名称:stash,代码行数:23,代码来源:libcore.py

示例9: getConfig

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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() 
开发者ID:xtiankisutsa,项目名称:MARA_Framework,代码行数:22,代码来源:common.py

示例10: writeKey

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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 
开发者ID:xtiankisutsa,项目名称:MARA_Framework,代码行数:23,代码来源:common.py

示例11: WriteErrorLog

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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() 
开发者ID:pynadath,项目名称:psychsim,代码行数:7,代码来源:robot.py

示例12: WriteLogData

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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() 
开发者ID:pynadath,项目名称:psychsim,代码行数:11,代码来源:robot.py

示例13: WriteErrorLog

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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() 
开发者ID:pynadath,项目名称:psychsim,代码行数:7,代码来源:wpRobot.py

示例14: WriteLogData

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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() 
开发者ID:pynadath,项目名称:psychsim,代码行数:10,代码来源:wpRobot.py

示例15: writeTmp

# 需要导入模块: import fileinput [as 别名]
# 或者: from fileinput import close [as 别名]
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 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:9,代码来源:test_fileinput.py


注:本文中的fileinput.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。