Python fileinput 模块,isfirstline() 实例源码

我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用fileinput.isfirstline()

项目:python-3-for-absolute-begs    作者:Apress    | 项目源码 | 文件源码
def rewritefile(fip):
    """Input:  fip, filename; expected to live in the
    current directory.  If the first line begins with
    #!, the line is replaced.  If it doesn't, then
    the proper #! line is prepended to the file.
    Existing file modes are preserved (that's what
    the chmod() call does), but the owner of the
    original file may change to whoever is running
    this script; that may be root on a Unix system.
    """
    global pbang
    mode = os.stat(fip)[ST_MODE]
    for line in fileinput.input(fip, inplace = 1):
    if fileinput.isfirstline():
        if line [: 2] == "#!":
        sys.stdout.write(pbang + "\n")
        else:
        sys.stdout.write(pbang + "\n")
        sys.stdout.write(line)
    else:
        sys.stdout.write(line)
    fileinput.close()
    os.chmod(fip, mode)
项目:core-python    作者:yidao620c    | 项目源码 | 文件源码
def t06():
    """??fileinput?????"""
    for line in fileinput.input(glob.glob("d*.txt"), inplace=1):
        if fileinput.isfirstline():
            print('-' * 20, 'Reading %s...' % fileinput.filename(), '-' * 20)
        print(str(fileinput.lineno()) + ': ' + line.rstrip().upper())
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def isfirstline(self):
        self.invocation_counts["isfirstline"] += 1
        return self.return_values["isfirstline"]
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_state_is_None(self):
        """Tests fileinput.isfirstline() when fileinput._state is None.
           Ensure that it raises RuntimeError with a meaningful error message
           and does not modify fileinput._state"""
        fileinput._state = None
        with self.assertRaises(RuntimeError) as cm:
            fileinput.isfirstline()
        self.assertEqual(("no active input()",), cm.exception.args)
        self.assertIsNone(fileinput._state)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_state_is_not_None(self):
        """Tests fileinput.isfirstline() when fileinput._state is not None.
           Ensure that it invokes fileinput._state.isfirstline() exactly once,
           returns whatever it returns, and does not modify fileinput._state
           to point to a different object."""
        isfirstline_retval = object()
        instance = MockFileInput()
        instance.return_values["isfirstline"] = isfirstline_retval
        fileinput._state = instance
        retval = fileinput.isfirstline()
        self.assertExactlyOneInvocation(instance, "isfirstline")
        self.assertIs(retval, isfirstline_retval)
        self.assertIs(fileinput._state, instance)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def isfirstline(self):
        self.invocation_counts["isfirstline"] += 1
        return self.return_values["isfirstline"]
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_state_is_None(self):
        """Tests fileinput.isfirstline() when fileinput._state is None.
           Ensure that it raises RuntimeError with a meaningful error message
           and does not modify fileinput._state"""
        fileinput._state = None
        with self.assertRaises(RuntimeError) as cm:
            fileinput.isfirstline()
        self.assertEqual(("no active input()",), cm.exception.args)
        self.assertIsNone(fileinput._state)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_state_is_not_None(self):
        """Tests fileinput.isfirstline() when fileinput._state is not None.
           Ensure that it invokes fileinput._state.isfirstline() exactly once,
           returns whatever it returns, and does not modify fileinput._state
           to point to a different object."""
        isfirstline_retval = object()
        instance = MockFileInput()
        instance.return_values["isfirstline"] = isfirstline_retval
        fileinput._state = instance
        retval = fileinput.isfirstline()
        self.assertExactlyOneInvocation(instance, "isfirstline")
        self.assertIs(retval, isfirstline_retval)
        self.assertIs(fileinput._state, instance)
项目:python-3-for-absolute-begs    作者:Apress    | 项目源码 | 文件源码
def fixdirectory(d):
    dlist = os.listdir(d)
    nfiles = 0
    for i in dlist:
        if i == nm:
        continue
        if len(i)> 4:
            fname = d + "/" + i
        if fname[-3:] == ".py":
            sys.stderr.write("Checking " + fname + "...\n")
            for line in fileinput.input(fname):
            if fileinput.isfirstline():
                if line[: -1] != pbang:
                fileinput.close()
                t = os.access(fname, os.W_OK)
                if t == 0:
                    sys.stderr.write(fname + " is not writable; skipping.\n")
                else:
                    sys.stderr.write("Modifying " + fname + "...\n")
                    rewritefile(fname)
                    nfiles = nfiles + 1
                break
                else:
                fileinput.close()
                break
    return nfiles
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def isfirstline(self):
        self.invocation_counts["isfirstline"] += 1
        return self.return_values["isfirstline"]
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_state_is_None(self):
        """Tests fileinput.isfirstline() when fileinput._state is None.
           Ensure that it raises RuntimeError with a meaningful error message
           and does not modify fileinput._state"""
        fileinput._state = None
        with self.assertRaises(RuntimeError) as cm:
            fileinput.isfirstline()
        self.assertEqual(("no active input()",), cm.exception.args)
        self.assertIsNone(fileinput._state)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_state_is_not_None(self):
        """Tests fileinput.isfirstline() when fileinput._state is not None.
           Ensure that it invokes fileinput._state.isfirstline() exactly once,
           returns whatever it returns, and does not modify fileinput._state
           to point to a different object."""
        isfirstline_retval = object()
        instance = MockFileInput()
        instance.return_values["isfirstline"] = isfirstline_retval
        fileinput._state = instance
        retval = fileinput.isfirstline()
        self.assertExactlyOneInvocation(instance, "isfirstline")
        self.assertIs(retval, isfirstline_retval)
        self.assertIs(fileinput._state, instance)
项目:docgen    作者:jpwarren    | 项目源码 | 文件源码
def replace_tags(filenames, tagdict={}, dry_run=False):
    """
    Update known tags in a list of files by modifying
    them in place.
    Always updates the ##COPYRIGHT## tag with the
    contents of the COPYRIGHT file.
    @param tagdict: a dictionary of tags to search for
    and the value that the tag should be replaced with.

    Only one tag should be used per line as this function
    is quite stupid and looks for a line starting with the
    tag, ignoring the rest of the line and replacing the
    whole line with tag = tag_value.
    """
    copyright_file = 'COPYRIGHT'
    copydata = open(copyright_file).read()

    for line in fileinput.input(filenames, inplace=True):
        matched = False

        # replace python #! line
        if fileinput.isfirstline():
            match = first_line_re.match(line)
            if match:
                matched = True
                post_interp = match.group(1) or ''
                if not dry_run:
                    sys.stdout.write("#!%s%s\n" % (os.path.join(
                        sysconfig.get_config_var("BINDIR"),
                        "python" + sysconfig.get_config_var("EXE")),
                                                   post_interp))
                    pass
                pass
            else:
                if not dry_run:
                    sys.stdout.write(line)
                    pass
                continue
            pass


        if line.startswith('##COPYRIGHT##'):
            if not dry_run:
                sys.stdout.write(copydata)
            matched = True
            continue

        for tag in tagdict:
            if line.startswith(tag):
                if not dry_run:
                    sys.stdout.write("%s = '%s'\n" % (tag, tagdict[tag]))
                matched = True
                break

        # this only happens if nothing matches
        if not matched:
            if not dry_run:
                sys.stdout.write(line)