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


Python linecache.getlines方法代码示例

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


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

示例1: _patch_linecache_for_source_highlight

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def _patch_linecache_for_source_highlight(self):
        orig = pdb.linecache.getlines

        def wrapped_getlines(filename, globals):
            """Wrap linecache.getlines to highlight source (for do_list)."""
            old_cache = pdb.linecache.cache.pop(filename, None)
            try:
                lines = orig(filename, globals)
            finally:
                if old_cache:
                    pdb.linecache.cache[filename] = old_cache
            source = self.format_source("".join(lines))

            if sys.version_info < (3,):
                source = self.try_to_encode(source)

            return source.splitlines(True)

        pdb.linecache.getlines = wrapped_getlines

        try:
            yield
        finally:
            pdb.linecache.getlines = orig 
开发者ID:pdbpp,项目名称:pdbpp,代码行数:26,代码来源:pdbpp.py

示例2: test_proceed_with_fake_filename

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def test_proceed_with_fake_filename(self):
        '''doctest monkeypatches linecache to enable inspection'''
        fn, source = '<test>', 'def x(): pass\n'
        getlines = linecache.getlines
        def monkey(filename, module_globals=None):
            if filename == fn:
                return source.splitlines(True)
            else:
                return getlines(filename, module_globals)
        linecache.getlines = monkey
        try:
            ns = {}
            exec compile(source, fn, 'single') in ns
            inspect.getsource(ns["x"])
        finally:
            linecache.getlines = getlines 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:18,代码来源:test_inspect.py

示例3: getlines

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def getlines(filename, module_globals=None):
        """Get the lines (as unicode) for a file from the cache.
        Update the cache if it doesn't contain an entry for this file already."""
        filename = py3compat.cast_bytes(filename, sys.getfilesystemencoding())
        lines = linecache.getlines(filename, module_globals=module_globals)
        
        # The bits we cache ourselves can be unicode.
        if (not lines) or isinstance(lines[0], unicode):
            return lines
        
        readline = openpy._list_readline(lines)
        try:
            encoding, _ = openpy.detect_encoding(readline)
        except SyntaxError:
            encoding = 'ascii'
        return [l.decode(encoding, 'replace') for l in lines]

    # This is a straight copy of linecache.getline 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:20,代码来源:ulinecache.py

示例4: search

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def search(self, argv):
        """search <pattern>
    Search the source file for the regular expression pattern."""
        patt = re.compile(" ".join(argv[1:]))
        filename = self._dbg.curframe.f_code.co_filename
        if self._dbg.lineno is None:
            start = 0
        else:
            start = max(0,  self._dbg.lineno - 9)
        lines = linecache.getlines(filename)[start:]
        for lineno, line in enumerate(lines):
            mo = patt.search(line)
            if mo:
                self._print_source(filename, lineno+start-10, lineno+start+10)
                return
        else:
            self._print("Pattern not found.") 
开发者ID:kdart,项目名称:pycopia,代码行数:19,代码来源:debugger.py

示例5: search

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def search(self, argv):
        """search <pattern>
    Search the source file for the regular expression pattern."""
        patt = re.compile(" ".join(argv[1:]))
        filename = self._dbg.curframe.f_code.co_filename
        if self._dbg.lineno is None:
            start = 0
        else:
            start = max(0,  self._dbg.lineno - 9)
        lines = linecache.getlines(filename)[start:]
        for lineno, line in enumerate(lines):
            #line = linecache.getline(filename, lineno)
            mo = patt.search(line)
            if mo:
                self._print_source(filename, lineno+start-10, lineno+start+10)
                return
        else:
            self._print("Pattern not found.") 
开发者ID:kdart,项目名称:pycopia,代码行数:20,代码来源:debugger.py

示例6: test_proceed_with_fake_filename

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def test_proceed_with_fake_filename(self):
        '''doctest monkeypatches linecache to enable inspection'''
        fn, source = '<test>', 'def x(): pass\n'
        getlines = linecache.getlines
        def monkey(filename, module_globals=None):
            if filename == fn:
                return source.splitlines(keepends=True)
            else:
                return getlines(filename, module_globals)
        linecache.getlines = monkey
        try:
            ns = {}
            exec(compile(source, fn, 'single'), ns)
            inspect.getsource(ns["x"])
        finally:
            linecache.getlines = getlines 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:18,代码来源:test_inspect.py

示例7: for_filename

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def for_filename(cls, filename, module_globals=None, use_cache=True):
        source_cache = cls._class_local('__source_cache', {})
        if use_cache:
            try:
                return source_cache[filename]
            except KeyError:
                pass

        if isinstance(filename, Path):
            filename = str(filename)

        if not use_cache:
            linecache.checkcache(filename)

        lines = tuple(linecache.getlines(filename, module_globals))
        result = source_cache[filename] = cls._for_filename_and_lines(filename, lines)
        return result 
开发者ID:alexmojaki,项目名称:executing,代码行数:19,代码来源:executing.py

示例8: test_getline

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def test_getline(self):
        getline = linecache.getline

        # Bad values for line number should return an empty string
        self.assertEqual(getline(FILENAME, 2**15), EMPTY)
        self.assertEqual(getline(FILENAME, -1), EMPTY)

        # Float values currently raise TypeError, should it?
        self.assertRaises(TypeError, getline, FILENAME, 1.1)

        # Bad filenames should return an empty string
        self.assertEqual(getline(EMPTY, 1), EMPTY)
        self.assertEqual(getline(INVALID_NAME, 1), EMPTY)

        # Check module loading
        for entry in MODULES:
            filename = os.path.join(MODULE_PATH, entry) + '.py'
            with open(filename) as file:
                for index, line in enumerate(file):
                    self.assertEqual(line, getline(filename, index + 1))

        # Check that bogus data isn't returned (issue #1309567)
        empty = linecache.getlines('a/b/c/__init__.py')
        self.assertEqual(empty, []) 
开发者ID:bkerler,项目名称:android_universal,代码行数:26,代码来源:test_linecache.py

示例9: test_getline

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def test_getline(self):
        getline = linecache.getline

        # Bad values for line number should return an empty string
        self.assertEqual(getline(FILENAME, 2**15), EMPTY)
        self.assertEqual(getline(FILENAME, -1), EMPTY)

        # Float values currently raise TypeError, should it?
        self.assertRaises(TypeError, getline, FILENAME, 1.1)

        # Bad filenames should return an empty string
        self.assertEqual(getline(EMPTY, 1), EMPTY)
        self.assertEqual(getline(INVALID_NAME, 1), EMPTY)

        # Check whether lines correspond to those from file iteration
        for entry in TESTS:
            filename = os.path.join(TEST_PATH, entry) + '.py'
            for index, line in enumerate(open(filename)):
                self.assertEqual(line, getline(filename, index + 1))

        # Check module loading
        for entry in MODULES:
            filename = os.path.join(MODULE_PATH, entry) + '.py'
            for index, line in enumerate(open(filename)):
                self.assertEqual(line, getline(filename, index + 1))

        # Check that bogus data isn't returned (issue #1309567)
        empty = linecache.getlines('a/b/c/__init__.py')
        self.assertEqual(empty, []) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:31,代码来源:test_linecache.py

示例10: test_no_ending_newline

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def test_no_ending_newline(self):
        self.addCleanup(support.unlink, support.TESTFN)
        with open(support.TESTFN, "w") as fp:
            fp.write(SOURCE_3)
        lines = linecache.getlines(support.TESTFN)
        self.assertEqual(lines, ["\n", "def f():\n", "    return 3\n"]) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:8,代码来源:test_linecache.py

示例11: test_memoryerror

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def test_memoryerror(self):
        lines = linecache.getlines(FILENAME)
        self.assertTrue(lines)
        def raise_memoryerror(*args, **kwargs):
            raise MemoryError
        with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
            lines2 = linecache.getlines(FILENAME)
        self.assertEqual(lines2, lines)

        linecache.clearcache()
        with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
            lines3 = linecache.getlines(FILENAME)
        self.assertEqual(lines3, [])
        self.assertEqual(linecache.getlines(FILENAME), lines) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:16,代码来源:test_linecache.py

示例12: load_source

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def load_source(self, window=3, lines=None):
        self.lines = self.line_numbers = None

        if (self.lineno and
                ((self.filename and not self.filename.startswith('<') and
                    not self.filename.endswith('>')) or lines)):

            lineno = self.lineno

            if not lines:
                linecache.checkcache(self.filename)
                sourcelines = linecache.getlines(self.filename, globals())
            else:
                sourcelines = lines

            lines = []
            line_numbers = []

            start = max(1, lineno - window)
            end = min(len(sourcelines), lineno + window) + 1
            for i in range(start, end):
                lines.append(sourcelines[i - 1].rstrip())
                line_numbers.append(i)

            if lines:
                self.lines = checked.CheckedList[str](lines)
                self.line_numbers = checked.CheckedList[int](line_numbers) 
开发者ID:edgedb,项目名称:edgedb,代码行数:29,代码来源:lang.py

示例13: _fixed_getframes

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def _fixed_getframes(etb, context=1, tb_offset=0):
    LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5

    records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))

    # If the error is at the console, don't build any context, since it would
    # otherwise produce 5 blank lines printed out (there is no file at the
    # console)
    rec_check = records[tb_offset:]
    try:
        rname = rec_check[0][1]
        if rname == '<ipython console>' or rname.endswith('<string>'):
            return rec_check
    except IndexError:
        pass

    aux = traceback.extract_tb(etb)
    assert len(records) == len(aux)
    for i, (file, lnum, _, _) in enumerate(aux):
        maybe_start = lnum - 1 - context // 2
        start = max(maybe_start, 0)
        end = start + context
        lines = linecache.getlines(file)[start:end]
        buf = list(records[i])
        buf[LNUM_POS] = lnum
        buf[INDEX_POS] = lnum - 1 - start
        buf[LINES_POS] = lines
        records[i] = tuple(buf)
    return records[tb_offset:] 
开发者ID:flennerhag,项目名称:mlens,代码行数:31,代码来源:format_stack.py

示例14: format_outer_frames

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def format_outer_frames(context=5, stack_start=None, stack_end=None,
                        ignore_ipython=True):
    LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
    records = inspect.getouterframes(inspect.currentframe())
    output = list()

    for i, (frame, filename, line_no, func_name, lines, index) \
                                                in enumerate(records):
        # Look inside the frame's globals dictionary for __file__, which should
        # be better.
        better_fn = frame.f_globals.get('__file__', None)
        if isinstance(better_fn, str):
            # Check the type just in case someone did something weird with
            # __file__. It might also be None if the error occurred during
            # import.
            filename = better_fn
            if filename.endswith('.pyc'):
                filename = filename[:-4] + '.py'
        if ignore_ipython:
            # Hack to avoid printing the internals of IPython
            if (os.path.basename(filename) in ('iplib.py', 'py3compat.py')
                        and func_name in ('execfile', 'safe_execfile', 'runcode')):
                break
        maybe_start = line_no - 1 - context // 2
        start = max(maybe_start, 0)
        end = start + context
        lines = linecache.getlines(filename)[start:end]
        buf = list(records[i])
        buf[LNUM_POS] = line_no
        buf[INDEX_POS] = line_no - 1 - start
        buf[LINES_POS] = lines
        output.append(tuple(buf))
    return '\n'.join(format_records(output[stack_end:stack_start:-1])) 
开发者ID:flennerhag,项目名称:mlens,代码行数:35,代码来源:format_stack.py

示例15: getline

# 需要导入模块: import linecache [as 别名]
# 或者: from linecache import getlines [as 别名]
def getline(filename, lineno, module_globals=None):
        lines = getlines(filename, module_globals)
        if 1 <= lineno <= len(lines):
            return lines[lineno-1]
        else:
            return '' 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:8,代码来源:ulinecache.py


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