Python fileinput.lineno() Examples

The following are 22 code examples of fileinput.lineno(). 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 Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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: more.py    From stash with MIT License 6 votes vote down vote up
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 #3
Source File: more.py    From stash with MIT License 6 votes vote down vote up
def main(args):
    parser = argparse.ArgumentParser(
        description=__doc__,
        epilog='This is inefficient for long input, as StaSh pipes do not multitask'
    )
    parser.add_argument('file', help='files to display ("-" is stdin is default)', action='store', nargs='*')
    parser.add_argument('-p', '--pageno', help='number screen pages cumulatively', action='store_true')
    parser.add_argument('-l', '--lineno', help='number lines cumulatively', action='store_true')
    parser.add_argument('-f', '--filename', help='label lines by filename', action='store_true')
    parser.add_argument('-n', '--filelineno', '-#', help='number lines per file', action='store_true')
    parser.add_argument(
        '-s',
        '--pagesize',
        help='number of lines per screen page (0 for no pagination)',
        action='store',
        type=int,
        default=40
    )  # TODO: use actual number of lines on screen for dynamic screen page size
    parser.add_argument('-c', '--clear', help='clear terminal screen before each screen page', action='store_true')
    ns = parser.parse_args(args)
    ns.line = True
    fmt = ' '.join('{' + var + '}' for var in 'pageno lineno filename filelineno line'.split() if getattr(ns, var))
    more(ns.file, ns.pagesize, ns.clear, fmt) 
Example #4
Source File: test_fileinput.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: test_fileinput.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
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: test_fileinput.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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) 
Example #7
Source File: objdump2vmh.py    From pydgin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def error( self, msg = "" ):
    if ( msg ): print("\n ERROR: %s" % msg)
    print("")
    for line in fileinput.input(sys.argv[0]):
      if ( not re.match( "#", line ) ): sys.exit(msg != "")
      if ((fileinput.lineno() == 3) or (fileinput.lineno() > 4)):
        print( re.sub( "^#", "", line.rstrip("\n") ) ) 
Example #8
Source File: objdump2vmh-cache.py    From pydgin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def error( self, msg = "" ):
    if ( msg ): print("\n ERROR: %s" % msg)
    print("")
    for line in fileinput.input(sys.argv[0]):
      if ( not re.match( "#", line ) ): sys.exit(msg != "")
      if ((fileinput.lineno() == 3) or (fileinput.lineno() > 4)):
        print( re.sub( "^#", "", line.rstrip("\n") ) ) 
Example #9
Source File: objdump2vmh.py    From pydgin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def error( self, msg = "" ):
    if ( msg ): print("\n ERROR: %s" % msg)
    print("")
    for line in fileinput.input(sys.argv[0]):
      if ( not re.match( "#", line ) ): sys.exit(msg != "")
      if ((fileinput.lineno() == 3) or (fileinput.lineno() > 4)):
        print( re.sub( "^#", "", line.rstrip("\n") ) ) 
Example #10
Source File: test_fileinput.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_state_is_None(self):
        """Tests fileinput.lineno() 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.lineno()
        self.assertEqual(("no active input()",), cm.exception.args)
        self.assertIsNone(fileinput._state) 
Example #11
Source File: test_fileinput.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def lineno(self):
        self.invocation_counts["lineno"] += 1
        return self.return_values["lineno"] 
Example #12
Source File: test_fileinput.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #13
Source File: test_fileinput.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #14
Source File: test_fileinput.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_state_is_None(self):
        """Tests fileinput.lineno() 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.lineno()
        self.assertEqual(("no active input()",), cm.exception.args)
        self.assertIsNone(fileinput._state) 
Example #15
Source File: test_fileinput.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def lineno(self):
        self.invocation_counts["lineno"] += 1
        return self.return_values["lineno"] 
Example #16
Source File: test_fileinput.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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) 
Example #17
Source File: test_fileinput.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_state_is_None(self):
        """Tests fileinput.lineno() 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.lineno()
        self.assertEqual(("no active input()",), cm.exception.args)
        self.assertIsNone(fileinput._state) 
Example #18
Source File: test_fileinput.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def lineno(self):
        self.invocation_counts["lineno"] += 1
        return self.return_values["lineno"] 
Example #19
Source File: test_fileinput.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #20
Source File: test_fileinput.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #21
Source File: base.py    From dyc with MIT License 5 votes vote down vote up
def _is_line_part_of_patches(self, lineno, line, patches):
        """
        Checks if a line is part of the patch
        Parameters
        ----------
        int lineno: Line number
        str line: Line text in a patch
        list patches: List of patches
        """
        result = False
        for change in patches:
            start, end = change.get("hunk")
            if start <= lineno <= end:
                patch = change.get("patch")
                found = filter(lambda l: line.replace("\n", "") == l, patch.split("\n"))
                if found:
                    result = True
                    break

                # Try to catch unusual declared methods
                broken_lines = line.split("\n")
                if len(broken_lines) and not is_one_line_method(
                    broken_lines[0], self.config.get("keywords")
                ):
                    result = True
                    break
        return result 
Example #22
Source File: base.py    From dyc with MIT License 4 votes vote down vote up
def initialize(self, change=None):
        """
        The Builder's main method. It stores all the changes that needs to be made
        in `self.details` for a file. Which would then be used to add Docstrings to.
        """
        result = dict()

        patches = []
        if change:
            patches = change.get("additions")

        fileLines = list(fileinput.input(self.filename))
        i = 0

        for line in fileinput.input(self.filename):
            filename = fileinput.filename()
            lineno = fileinput.lineno()
            keywords = self.config.get("keywords")
            foundList = [
                word.lstrip() for word in line.split(" ") if word.lstrip() in keywords
            ]
            found = len(foundList) > 0 and not is_comment(
                line, self.config.get('comments')
            )
            # Checking an unusual format in method declaration
            if foundList:
                openP = line.count("(")
                closeP = line.count(")")
                if openP == closeP:
                    pass
                else:
                    pos = i
                    while openP != closeP:
                        pos += 1
                        line += fileLines[pos]
                        openP = line.count("(")
                        closeP = line.count(")")
                    lineno = pos + 1
            i = i + 1

            if change and found:
                found = self._is_line_part_of_patches(lineno, line, patches)

            if not self.details.get(filename):
                self.details[filename] = dict()

            if found:
                length = get_file_lines(filename)
                result = self.extract_and_set_information(
                    filename, lineno, line, length
                )
                if self.validate(result):
                    self.details[filename][result.name] = result