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

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

项目:REPIC    作者:dpinney    | 项目源码 | 文件源码
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)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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)
项目:core-python    作者:yidao620c    | 项目源码 | 文件源码
def t08():
    """??fileinput?????grep???"""
    import re
    pattern = re.compile(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}')
    for line in fileinput.input('data.txt', backup='.bak', inplace=1):
        if pattern.search(line):
            print(fileinput.filename(), fileinput.filelineno(), line)
项目:Django-Web-Development-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def backport(rootdir="."):
    for folder, subs, files in os.walk(rootdir):
        for filename in files:
            src_filename = os.path.join(folder, filename)
            # Skip non python files
            if not src_filename.endswith(".py"):
                continue
            if (__file__ and os.path.basename(src_filename) ==
                    os.path.basename(__file__)):
                continue
            print(src_filename)
            last_class = ""
            for line in fileinput.input(src_filename, inplace=True):
                if fileinput.filelineno() == 1:
                    if line.startswith("#!"):
                        print(line, end="")
                        print("from __future__ import unicode_literals")
                    else:
                        print("from __future__ import unicode_literals")
                        print(line, end="")
                    continue
                if line.strip().startswith("class"):
                    last_class = line.strip().split()[1]
                    last_class = re.match(r'([a-zA-Z0-9]+)',
                                          last_class).group(1)
                if "__str__(" in line:
                    line = line.replace("__str__(", "__unicode__(")
                if "super()" in line:
                    old_super = "super({}, self)".format(last_class)
                    line = line.replace("super()", old_super)
                print(line, end="")
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_files_that_dont_end_with_newline(self):
        t1 = t2 = None
        try:
            t1 = writeTmp(1, ["A\nB\nC"])
            t2 = writeTmp(2, ["D\nE\nF"])
            fi = FileInput(files=(t1, t2))
            lines = list(fi)
            self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
            self.assertEqual(fi.filelineno(), 3)
            self.assertEqual(fi.lineno(), 6)
        finally:
            remove_tempfiles(t1, t2)

##     def test_unicode_filenames(self):
##         # XXX A unicode string is always returned by writeTmp.
##         #     So is this needed?
##         try:
##             t1 = writeTmp(1, ["A\nB"])
##             encoding = sys.getfilesystemencoding()
##             if encoding is None:
##                 encoding = 'ascii'
##             fi = FileInput(files=str(t1, encoding))
##             lines = list(fi)
##             self.assertEqual(lines, ["A\n", "B"])
##         finally:
##             remove_tempfiles(t1)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_context_manager(self):
        try:
            t1 = writeTmp(1, ["A\nB\nC"])
            t2 = writeTmp(2, ["D\nE\nF"])
            with FileInput(files=(t1, t2)) as fi:
                lines = list(fi)
            self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
            self.assertEqual(fi.filelineno(), 3)
            self.assertEqual(fi.lineno(), 6)
            self.assertEqual(fi._files, ())
        finally:
            remove_tempfiles(t1, t2)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def filelineno(self):
        self.invocation_counts["filelineno"] += 1
        return self.return_values["filelineno"]
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_state_is_None(self):
        """Tests fileinput.filelineno() 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.filelineno()
        self.assertEqual(("no active input()",), cm.exception.args)
        self.assertIsNone(fileinput._state)
项目:wende    作者:h404bi    | 项目源码 | 文件源码
def load_data(filenames):
    """ ???????????
    :param filenames: ??????
    :return: Bunch ????. See:
        http://scikit-learn.org/stable/datasets/index.html#datasets
    """
    # ??????
    data = []
    # ???????????
    target = []
    # ????
    target_names = {}
    # ????????????HUM,???????
    data_re = re.compile(r'(\w+),(.+)')

    for line in fileinput.input(filenames):
        match = data_re.match(line.decode('utf-8'))
        if not match:
            raise Exception("Invalid format in dataset {} at line {}"
                            .format(fileinput.filename(),
                                    fileinput.filelineno()))

        label, text = match.group(1), match.group(2)

        if label not in target_names:
            target_names[label] = len(target_names)
        # ??????????`HUM`, `LOC`, etc.?
        target.append(label)
        # ?????????????{'HUM': 1, 'LOC': 2}?
        # target.append(target_names[label])
        data.append(text)

    return Bunch(
        data=numpy.array(data),
        target=numpy.array(target),
        target_names=numpy.array([k for k in target_names]),
    )
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_files_that_dont_end_with_newline(self):
        t1 = t2 = None
        try:
            t1 = writeTmp(1, ["A\nB\nC"])
            t2 = writeTmp(2, ["D\nE\nF"])
            fi = FileInput(files=(t1, t2))
            lines = list(fi)
            self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
            self.assertEqual(fi.filelineno(), 3)
            self.assertEqual(fi.lineno(), 6)
        finally:
            remove_tempfiles(t1, t2)

##     def test_unicode_filenames(self):
##         # XXX A unicode string is always returned by writeTmp.
##         #     So is this needed?
##         try:
##             t1 = writeTmp(1, ["A\nB"])
##             encoding = sys.getfilesystemencoding()
##             if encoding is None:
##                 encoding = 'ascii'
##             fi = FileInput(files=str(t1, encoding))
##             lines = list(fi)
##             self.assertEqual(lines, ["A\n", "B"])
##         finally:
##             remove_tempfiles(t1)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_context_manager(self):
        try:
            t1 = writeTmp(1, ["A\nB\nC"])
            t2 = writeTmp(2, ["D\nE\nF"])
            with FileInput(files=(t1, t2)) as fi:
                lines = list(fi)
            self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
            self.assertEqual(fi.filelineno(), 3)
            self.assertEqual(fi.lineno(), 6)
            self.assertEqual(fi._files, ())
        finally:
            remove_tempfiles(t1, t2)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def filelineno(self):
        self.invocation_counts["filelineno"] += 1
        return self.return_values["filelineno"]
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_state_is_None(self):
        """Tests fileinput.filelineno() 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.filelineno()
        self.assertEqual(("no active input()",), cm.exception.args)
        self.assertIsNone(fileinput._state)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_files_that_dont_end_with_newline(self):
        t1 = t2 = None
        try:
            t1 = writeTmp(1, ["A\nB\nC"])
            t2 = writeTmp(2, ["D\nE\nF"])
            fi = FileInput(files=(t1, t2))
            lines = list(fi)
            self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
            self.assertEqual(fi.filelineno(), 3)
            self.assertEqual(fi.lineno(), 6)
        finally:
            remove_tempfiles(t1, t2)

##     def test_unicode_filenames(self):
##         # XXX A unicode string is always returned by writeTmp.
##         #     So is this needed?
##         try:
##             t1 = writeTmp(1, ["A\nB"])
##             encoding = sys.getfilesystemencoding()
##             if encoding is None:
##                 encoding = 'ascii'
##             fi = FileInput(files=str(t1, encoding))
##             lines = list(fi)
##             self.assertEqual(lines, ["A\n", "B"])
##         finally:
##             remove_tempfiles(t1)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_context_manager(self):
        try:
            t1 = writeTmp(1, ["A\nB\nC"])
            t2 = writeTmp(2, ["D\nE\nF"])
            with FileInput(files=(t1, t2)) as fi:
                lines = list(fi)
            self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
            self.assertEqual(fi.filelineno(), 3)
            self.assertEqual(fi.lineno(), 6)
            self.assertEqual(fi._files, ())
        finally:
            remove_tempfiles(t1, t2)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def filelineno(self):
        self.invocation_counts["filelineno"] += 1
        return self.return_values["filelineno"]
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_state_is_None(self):
        """Tests fileinput.filelineno() 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.filelineno()
        self.assertEqual(("no active input()",), cm.exception.args)
        self.assertIsNone(fileinput._state)