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


Python linecache.getline方法代码示例

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


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

示例1: get_ip_geo_localization

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
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 
开发者ID:apache,项目名称:incubator-spot,代码行数:19,代码来源:geoloc.py

示例2: solution

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
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) 
开发者ID:iKevinY,项目名称:EulerPy,代码行数:22,代码来源:problem.py

示例3: _check_docstring

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
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) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:27,代码来源:docstyle.py

示例4: _header_check

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
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 
开发者ID:GEMScienceTools,项目名称:gmpe-smtk,代码行数:21,代码来源:simple_flatfile_parser_sara.py

示例5: _header_check

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
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 
开发者ID:GEMScienceTools,项目名称:gmpe-smtk,代码行数:21,代码来源:simple_flatfile_parser.py

示例6: extract_tb

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
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 
开发者ID:quora,项目名称:asynq,代码行数:26,代码来源:debug.py

示例7: lru_cache

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

示例8: ShowLineNo

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
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 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:18,代码来源:debugger.py

示例9: checkline

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
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 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:22,代码来源:pdb.py

示例10: test_show_warning_output

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
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) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:24,代码来源:test_warnings.py

示例11: test_formatwarning_unicode_msg

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
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)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:19,代码来源:test_warnings.py

示例12: test_showwarning

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

示例13: _convert_stack

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
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 
开发者ID:abhisuri97,项目名称:auto-alt-text-lambda-api,代码行数:25,代码来源:ops.py

示例14: add_geospatial_info

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
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 
开发者ID:apache,项目名称:incubator-spot,代码行数:37,代码来源:flow.py

示例15: __getitem__

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getline [as 别名]
def __getitem__(self, idx):
        line = linecache.getline(self.fn, idx + 1)
        return pybedtools.create_interval_from_list(line.strip().split("\t")) 
开发者ID:kipoi,项目名称:models,代码行数:5,代码来源:dataloader.py


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