Python linecache.getline() Examples

The following are 30 code examples for showing how to use linecache.getline(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module linecache , or try the search function .

Example 1
Project: incubator-spot   Author: apache   File: geoloc.py    License: Apache License 2.0 7 votes vote down vote up
def get_ip_geo_localization(self, ip):

        self._logger.debug("Getting {0} geo localization ".format(ip))
        if ip.strip() != "" and ip is not None:

            result = linecache.getline(self._ip_localization_file, bisect.bisect(self._ip_localization_ranges, Util.ip_to_int(ip)))
            result.strip('\n')

            reader = csv.reader([result])
            row = reader.next()

            geo_loc = ";".join(row[4:6]) + " " + ";".join(row[8:9])            
            domain = row[9:10][0]

            result = {"geo_loc": geo_loc, "domain": domain}

        return result 
Example 2
Project: EulerPy   Author: iKevinY   File: problem.py    License: MIT License 6 votes vote down vote up
def solution(self):
        """Returns the answer to a given problem"""
        num = self.num

        solution_file = os.path.join(EULER_DATA, 'solutions.txt')
        solution_line = linecache.getline(solution_file, num)

        try:
            answer = solution_line.split('. ')[1].strip()
        except IndexError:
            answer = None

        if answer:
            return answer
        else:
            msg = 'Answer for problem %i not found in solutions.txt.' % num
            click.secho(msg, fg='red')
            click.echo('If you have an answer, consider submitting a pull '
                       'request to EulerPy on GitHub.')
            sys.exit(1) 
Example 3
Project: linter-pylama   Author: AtomLinter   File: docstyle.py    License: MIT License 6 votes vote down vote up
def _check_docstring(self, node_type, node):
        docstring = node.doc
        if docstring and docstring[0] == '\n':
            self.add_message('docstring-first-line-empty', node=node,
                             args=(node_type,), confidence=HIGH)

        # Use "linecache", instead of node.as_string(), because the latter
        # looses the original form of the docstrings.

        if docstring:
            lineno = node.fromlineno + 1
            line = linecache.getline(node.root().file, lineno).lstrip()
            if line and line.find('"""') == 0:
                return
            if line and '\'\'\'' in line:
                quotes = '\'\'\''
            elif line and line[0] == '"':
                quotes = '"'
            elif line and line[0] == '\'':
                quotes = '\''
            else:
                quotes = False
            if quotes:
                self.add_message('bad-docstring-quotes', node=node,
                                 args=(node_type, quotes), confidence=HIGH) 
Example 4
Project: gmpe-smtk   Author: GEMScienceTools   File: simple_flatfile_parser_sara.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _header_check(self, headerslist):
        """
        Checks to see if any of the headers are missing, raises error if so.
        Also informs the user of redundent headers in the input file.
        """
        # Check which of the pre-defined headers are missing
        headers = Set((getline(self.filename, 1).rstrip("\n")).split(","))
        missing_headers = headerslist.difference(headers)
        if len(missing_headers) > 0:
            output_string = ", ".join([value for value in missing_headers])
            raise IOError("The following headers are missing from the input "
                          "file: %s" % output_string)

        additional_headers = headers.difference(headerslist)
        if len(additional_headers) > 0:
            for header in additional_headers:
                print("Header %s not recognised - ignoring this data!" %
                      header)
        return 
Example 5
Project: gmpe-smtk   Author: GEMScienceTools   File: simple_flatfile_parser.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _header_check(self):
        """
        Checks to see if any of the headers are missing, raises error if so.
        Also informs the user of redundent headers in the input file.
        """
        # Check which of the pre-defined headers are missing
        headers = Set((getline(self.filename, 1).rstrip("\n")).split(","))
        missing_headers = HEADER_LIST.difference(headers)
        if len(missing_headers) > 0:
            output_string = ", ".join([value for value in missing_headers])
            raise IOError("The following headers are missing from the input "
                          "file: %s" % output_string)

        additional_headers = headers.difference(HEADER_LIST)
        if len(additional_headers) > 0:
            for header in additional_headers:
                print("Header %s not recognised - ignoring this data!" %
                      header)
        return 
Example 6
Project: asynq   Author: quora   File: debug.py    License: Apache License 2.0 6 votes vote down vote up
def extract_tb(tb, limit=None):
    """This implementation is stolen from traceback module but respects __traceback_hide__."""
    if limit is None:
        if hasattr(sys, "tracebacklimit"):
            limit = sys.tracebacklimit
    tb_list = []
    n = 0
    while tb is not None and (limit is None or n < limit):
        f = tb.tb_frame
        if not _should_skip_frame(f):
            lineno = tb.tb_lineno
            co = f.f_code
            filename = co.co_filename
            name = co.co_name
            linecache.checkcache(filename)
            line = linecache.getline(filename, lineno, f.f_globals)
            if line:
                line = line.strip()
            else:
                line = None
            tb_list.append((filename, lineno, name, line))
        tb = tb.tb_next
        n = n + 1
    return tb_list 
Example 7
Project: pdbpp   Author: pdbpp   File: pdbpp.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def lru_cache(maxsize):
        """Simple cache (with no maxsize basically) for py27 compatibility.

        Given that pdb there uses linecache.getline for each line with
        do_list a cache makes a big differene."""

        def dec(fn, *args):
            cache = {}

            @wraps(fn)
            def wrapper(*args):
                key = args
                try:
                    ret = cache[key]
                except KeyError:
                    ret = cache[key] = fn(*args)
                return ret

            return wrapper

        return dec

# If it contains only _, digits, letters, [] or dots, it's probably side
# effects free. 
Example 8
Project: ironpython2   Author: IronLanguages   File: debugger.py    License: Apache License 2.0 6 votes vote down vote up
def ShowLineNo( self, filename, lineno ):
		wasOpen = editor.editorTemplate.FindOpenDocument(filename) is not None
		if os.path.isfile(filename) and scriptutils.JumpToDocument(filename, lineno):
			if not wasOpen:
				doc = editor.editorTemplate.FindOpenDocument(filename)
				if doc is not None:
					self.UpdateDocumentLineStates(doc)
					return 1
				return 0
			return 1
		else:
			# Can't find the source file - linecache may have it?
			import linecache
			line = linecache.getline(filename, lineno)
			print "%s(%d): %s" % (os.path.basename(filename), lineno, line[:-1].expandtabs(4))
			return 0 
Example 9
Project: ironpython2   Author: IronLanguages   File: pdb.py    License: Apache License 2.0 6 votes vote down vote up
def checkline(self, filename, lineno):
        """Check whether specified line seems to be executable.

        Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
        line or EOF). Warning: testing is not comprehensive.
        """
        # this method should be callable before starting debugging, so default
        # to "no globals" if there is no current frame
        globs = self.curframe.f_globals if hasattr(self, 'curframe') else None
        line = linecache.getline(filename, lineno, globs)
        if not line:
            print >>self.stdout, 'End of file'
            return 0
        line = line.strip()
        # Don't allow setting breakpoint at a blank line
        if (not line or (line[0] == '#') or
             (line[:3] == '"""') or line[:3] == "'''"):
            print >>self.stdout, '*** Blank or comment'
            return 0
        return lineno 
Example 10
Project: ironpython2   Author: IronLanguages   File: test_warnings.py    License: Apache License 2.0 6 votes vote down vote up
def test_show_warning_output(self):
        # With showarning() missing, make sure that output is okay.
        text = 'test show_warning'
        with original_warnings.catch_warnings(module=self.module):
            self.module.filterwarnings("always", category=UserWarning)
            del self.module.showwarning
            with test_support.captured_output('stderr') as stream:
                warning_tests.inner(text)
                result = stream.getvalue()
        self.assertEqual(result.count('\n'), 2,
                             "Too many newlines in %r" % result)
        first_line, second_line = result.split('\n', 1)
        expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
        first_line_parts = first_line.rsplit(':', 3)
        path, line, warning_class, message = first_line_parts
        line = int(line)
        self.assertEqual(expected_file, path)
        self.assertEqual(warning_class, ' ' + UserWarning.__name__)
        self.assertEqual(message, ' ' + text)
        expected_line = '  ' + linecache.getline(path, line).strip() + '\n'
        assert expected_line
        self.assertEqual(second_line, expected_line) 
Example 11
Project: ironpython2   Author: IronLanguages   File: test_warnings.py    License: Apache License 2.0 6 votes vote down vote up
def test_formatwarning_unicode_msg(self):
        message = u"msg"
        category = Warning
        file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
        line_num = 3
        file_line = linecache.getline(file_name, line_num).strip()
        format = "%s:%s: %s: %s\n  %s\n"
        expect = format % (file_name, line_num, category.__name__, message,
                            file_line)
        self.assertEqual(expect, self.module.formatwarning(message,
                                                category, file_name, line_num))
        # Test the 'line' argument.
        file_line += " for the win!"
        expect = format % (file_name, line_num, category.__name__, message,
                            file_line)
        self.assertEqual(expect, self.module.formatwarning(message,
                                    category, file_name, line_num, file_line)) 
Example 12
Project: ironpython2   Author: IronLanguages   File: test_warnings.py    License: Apache License 2.0 6 votes vote down vote up
def test_showwarning(self):
        file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
        line_num = 3
        expected_file_line = linecache.getline(file_name, line_num).strip()
        message = 'msg'
        category = Warning
        file_object = StringIO.StringIO()
        expect = self.module.formatwarning(message, category, file_name,
                                            line_num)
        self.module.showwarning(message, category, file_name, line_num,
                                file_object)
        self.assertEqual(file_object.getvalue(), expect)
        # Test 'line' argument.
        expected_file_line += "for the win!"
        expect = self.module.formatwarning(message, category, file_name,
                                            line_num, expected_file_line)
        file_object = StringIO.StringIO()
        self.module.showwarning(message, category, file_name, line_num,
                                file_object, expected_file_line)
        self.assertEqual(expect, file_object.getvalue()) 
Example 13
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: ops.py    License: MIT License 6 votes vote down vote up
def _convert_stack(stack):
  """Converts a stack extracted using _extract_stack() to a traceback stack.

  Args:
    stack: A list of n 4-tuples, (filename, lineno, name, frame_globals).

  Returns:
    A list of n 4-tuples (filename, lineno, name, code), where the code tuple
    element is calculated from the corresponding elements of the input tuple.
  """
  ret = []
  for filename, lineno, name, frame_globals in stack:
    linecache.checkcache(filename)
    line = linecache.getline(filename, lineno, frame_globals)
    if line:
      line = line.strip()
    else:
      line = None
    ret.append((filename, lineno, name, line))
  return ret


# pylint: disable=line-too-long 
Example 14
Project: incubator-spot   Author: apache   File: flow.py    License: Apache License 2.0 5 votes vote down vote up
def add_geospatial_info(iploc,inbound,outbound,twoway):
    iplist = ''
    if os.path.isfile(iploc):
        iplist = np.loadtxt(iploc,dtype=np.uint32,delimiter=',',usecols={0},\
        converters={0: lambda s: np.uint32(s.replace('"',''))})
    else:
        print "No iploc.csv file was found, Map View map won't be created"


    # get geospatial info, only when iplocation file is available
    if iplist != '':
        for srcip in outbound:
            reader = csv.reader([linecache.getline(\
            iploc, bisect.bisect(iplist,outbound[srcip]['ip_int'])).replace('\n','')])

            outbound[srcip]['geo'] = reader.next()
            reader = csv.reader([linecache.getline(\
            iploc, bisect.bisect(iplist,outbound[srcip]['dst_ip_int'])).replace('\n','')])
            outbound[srcip]['geo_dst'] = reader.next()

        for dstip in twoway:
            reader = csv.reader([linecache.getline(\
            iploc,bisect.bisect(iplist,twoway[dstip]['ip_int'])).replace('\n','')])
            twoway[dstip]['geo'] = reader.next()

        for srcip in inbound:
            reader = csv.reader([linecache.getline(\
            iploc, bisect.bisect(iplist,inbound[srcip]['ip_int'])).replace('\n','')])

            inbound[srcip]['geo'] = reader.next()
            reader = csv.reader([linecache.getline(\
            iploc, bisect.bisect(iplist,inbound[srcip]['src_ip_int'])).replace('\n','')])
            inbound[srcip]['geo_src'] = reader.next()

    return inbound,outbound,twoway 
Example 15
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 16
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 17
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 18
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 19
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 20
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 21
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 22
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 23
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 24
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 25
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 26
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 27
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 28
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 29
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
Example 30
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t"))