Python linecache 模块,getline() 实例源码

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

项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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
项目:alpha    作者:ArielHorwitz    | 项目源码 | 文件源码
def generatesurname(species):
    # check species
    if species == 1:
        sl=sum(1 for line in open('assets/Generators/NameGenerator/HumanSurnames.txt'))
        sr = random.randrange(sl)+1
        sn = linecache.getline('assets/Generators/NameGenerator/HumanSurnames.txt', sr)
        # Delete Newline at end
    elif species == 2:
        sl=sum(1 for line in open('assets/Generators/NameGenerator/RobotSurnames.txt'))
        sr = random.randrange(sl)+1
        sn = linecache.getline('assets/Generators/NameGenerator/RobotSurnames.txt', sr)
        # Delete Newline at end
    else:
        # error msg
        print('please specify species for name generator')
        return
    linecache.clearcache()
    sm = len(sn)-1
    lastname = sn[:sm]
    return lastname
# newname = Name('human',2)
# newsurname = Surname('human')
# print(newname,newsurname)
项目:pyrate-build    作者:pyrate-build    | 项目源码 | 文件源码
def format_exception(bfn, ex):
    import traceback, linecache
    exinfo = traceback.format_exception_only(ex.__class__, ex)
    if ex.__class__ == SyntaxError:
        exinfo = exinfo[1:]
        lineno = ex.lineno
        content = ''
        sys.stderr.write('Error while processing %s:%s\n\t%s\n' % (os.path.abspath(bfn), lineno, content.strip()))
    else:
        exec_line = None
        exloc = traceback.extract_tb(sys.exc_info()[2])
        for idx, entry in enumerate(exloc):
            if entry[3] is None:
                exec_line = idx
        if exec_line is not None:
            exloc = [(bfn, exloc[exec_line][1], '', linecache.getline(bfn, exloc[exec_line][1]))] + exloc[exec_line:]
        sys.stderr.write('Error while processing %s\n' % os.path.abspath(bfn))
        sys.stderr.write(str.join('', traceback.format_list(exloc)))
    sys.stderr.write(str.join('', exinfo))
    sys.exit(1)
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
def senddata(self):
        filename = "output.txt"
        fileit = open(filename, 'r')
        done = 0
        while not done:
            output = fileit.readline()
            if output != "":
                # 'text' is the value needed to be past to the php script to put in db
                # the form name is text which is a textarea
                params = urllib.urlencode({'text': output})
                headers = {"Content-type": "application/x-www-form-urlencoded",
                                "Accept": "text/plain"}
                conn = httplib.HTTPConnection(linecache.getline('info.txt', 1))
                conn.request("POST", "/filewrite.php", params, headers)
                response = conn.getresponse()
                print response.status, response.reason
                data = response.read()        
            else:
                done = 1
        fileit.close()
        return True
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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
项目:SegmentationService    作者:jingchaoluan    | 项目源码 | 文件源码
def tracing(f):
    """Enable tracing just within a function call."""
    def globaltrace(frame,why,arg):
        if why == "call": return localtrace
        return None
    def localtrace(frame, why, arg):
        if why == "line":
            fname = frame.f_code.co_filename
            lineno = frame.f_lineno
            base = os.path.basename(fname)
            print("%s(%s): %s" % (base, lineno,
                                  linecache.getline(fname, lineno)))
        return localtrace
    @wrap(f)
    def wrapper(*args,**kw):
        sys.settrace(globaltrace)
        result = f(*args,**kw)
        sys.settrace(None)
        return result
    return wrapper
项目:automation    作者:kubic-project    | 项目源码 | 文件源码
def format_dict(raw):
    output = []
    if raw['file'].startswith('./'):
        output.append(raw['file'][2:])
    else:
        output.append(raw['file'])

    output.append(raw['line'])
    output.append(raw['col'])
    output.append(raw['error_code'])

    output.append(raw['error_desc'].lstrip())

    code_string = linecache.getline(
        output[0],
        int(raw['line'])).lstrip().rstrip()

    output.append(code_string)

    return output
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
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
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
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
项目:true_review_web2py    作者:lucadealfaro    | 项目源码 | 文件源码
def post_mortem(self, t=None):
        # handling the default
        if t is None:
            # sys.exc_info() returns (type, value, traceback) if an exception is
            # being handled, otherwise it returns None
            t = sys.exc_info()[2]
            if t is None:
                raise ValueError("A valid traceback must be passed if no "
                                 "exception is being handled")
        self.reset()
        # get last frame:
        while t is not None:
            frame = t.tb_frame
            t = t.tb_next
            code, lineno = frame.f_code, frame.f_lineno
            filename = code.co_filename
            line = linecache.getline(filename, lineno)
            #(filename, lineno, "", current, line, )}

        self.interaction(frame)

    # console file-like object emulation
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def post_mortem(self, t=None):
        # handling the default
        if t is None:
            # sys.exc_info() returns (type, value, traceback) if an exception is
            # being handled, otherwise it returns None
            t = sys.exc_info()[2]
            if t is None:
                raise ValueError("A valid traceback must be passed if no "
                                 "exception is being handled")
        self.reset()
        # get last frame:
        while t is not None:
            frame = t.tb_frame
            t = t.tb_next
            code, lineno = frame.f_code, frame.f_lineno
            filename = code.co_filename
            line = linecache.getline(filename, lineno)
            #(filename, lineno, "", current, line, )}

        self.interaction(frame)

    # console file-like object emulation
项目:build-calibre    作者:kovidgoyal    | 项目源码 | 文件源码
def main():
    sys.frozen = 'windows_exe'
    sys.setdefaultencoding('utf-8')
    aliasmbcs()

    sys.meta_path.insert(0, PydImporter())
    sys.path_importer_cache.clear()

    import linecache
    def fake_getline(filename, lineno, module_globals=None):
        return ''
    linecache.orig_getline = linecache.getline
    linecache.getline = fake_getline

    abs__file__()

    add_calibre_vars()

    # Needed for pywintypes to be able to load its DLL
    sys.path.append(os.path.join(sys.app_dir, 'app', 'DLLs'))

    return run_entry_point()
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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:
            self.message('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] == "'''"):
            self.error('Blank or comment')
            return 0
        return lineno
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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 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)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_formatwarning(self):
        message = "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))
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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()
        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()
        self.module.showwarning(message, category, file_name, line_num,
                                file_object, expected_file_line)
        self.assertEqual(expect, file_object.getvalue())
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def load_stack(self, stack, index=None):
        self.stack = stack
        self.clear()
        for i in range(len(stack)):
            frame, lineno = stack[i]
            try:
                modname = frame.f_globals["__name__"]
            except:
                modname = "?"
            code = frame.f_code
            filename = code.co_filename
            funcname = code.co_name
            import linecache
            sourceline = linecache.getline(filename, lineno)
            sourceline = sourceline.strip()
            if funcname in ("?", "", None):
                item = "%s, line %d: %s" % (modname, lineno, sourceline)
            else:
                item = "%s.%s(), line %d: %s" % (modname, funcname,
                                                 lineno, sourceline)
            if i == index:
                item = "> " + item
            self.append(item)
        if index is not None:
            self.select(index)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def GetText(self):
        frame, lineno = self.info
        try:
            modname = frame.f_globals["__name__"]
        except:
            modname = "?"
        code = frame.f_code
        filename = code.co_filename
        funcname = code.co_name
        sourceline = linecache.getline(filename, lineno)
        sourceline = sourceline.strip()
        if funcname in ("?", "", None):
            item = "%s, line %d: %s" % (modname, lineno, sourceline)
        else:
            item = "%s.%s(...), line %d: %s" % (modname, funcname,
                                             lineno, sourceline)
        return item
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def __str__ (self):
        exc_type, exc_obj, exc_tb = sys.exc_info()
        if not exc_tb:
            return self.msg
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]


        src_line = str(linecache.getline(fname, exc_tb.tb_lineno))


        s = "\n******\n"
        s += "Error at {0}:{1} - '{2}'\n\n".format(format_text(fname, 'bold'), format_text(exc_tb.tb_lineno, 'bold'), format_text(src_line.strip(), 'bold'))
        s += "specific error:\n\n{0}\n".format(format_text(self.msg, 'bold'))



        return s
项目:Problematica-public    作者:TechMaz    | 项目源码 | 文件源码
def post_mortem(self, t=None):
        # handling the default
        if t is None:
            # sys.exc_info() returns (type, value, traceback) if an exception is
            # being handled, otherwise it returns None
            t = sys.exc_info()[2]
            if t is None:
                raise ValueError("A valid traceback must be passed if no "
                                 "exception is being handled")
        self.reset()
        # get last frame:
        while t is not None:
            frame = t.tb_frame
            t = t.tb_next
            code, lineno = frame.f_code, frame.f_lineno
            filename = code.co_filename
            line = linecache.getline(filename, lineno)
            #(filename, lineno, "", current, line, )}

        self.interaction(frame)

    # console file-like object emulation
项目:CIDDS    作者:markusring    | 项目源码 | 文件源码
def start_search(driver, keywords, var):
    try:
        # Determine the number of search terms and choose one randomly
        nb = file_len(keywords)
        rand = random.randint(1, nb)
        search = linecache.getline(keywords, rand)

        # Determine search field and enter search term
        elem = driver.find_element_by_name(var)
        elem.send_keys(search)
        elem.send_keys(Keys.RETURN)
        echoC(myName, "Searched: " + search)
        time.sleep(5)   
    except Exception as e:
        echoC(myName, "start_search() error: " + str(e))
        return -1
    return 0

# Click on a link based on the HTML tag name
项目:CIDDS    作者:markusring    | 项目源码 | 文件源码
def addAttachments(msg):
    attachments = []
    lines = file_len("packages/mailing/attachments.txt")
    nb = random.randint(0, lines)
    for i in range(0, nb-1):
        rand = random.randint(1, lines)
        att = linecache.getline("packages/mailing/attachments.txt", rand).replace ("\n", "")
        attachments.append(att)
    if nb > 0:
        for f in attachments or []:
            with open(f, "rb") as fil:
                part = MIMEBase('application', "octet-stream")
                part.set_payload(fil.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' %f)
                msg.attach(part)
        echoC(__name__, "Attachments attached")
    else:
        echoC(__name__, "No attachments")
    return msg
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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))
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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())
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def GetText(self):
        frame, lineno = self.info
        try:
            modname = frame.f_globals["__name__"]
        except:
            modname = "?"
        code = frame.f_code
        filename = code.co_filename
        funcname = code.co_name
        sourceline = linecache.getline(filename, lineno)
        sourceline = sourceline.strip()
        if funcname in ("?", "", None):
            item = "%s, line %d: %s" % (modname, lineno, sourceline)
        else:
            item = "%s.%s(...), line %d: %s" % (modname, funcname,
                                             lineno, sourceline)
        return item
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_formatwarning(self):
        message = "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))
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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())
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def GetText(self):
        frame, lineno = self.info
        try:
            modname = frame.f_globals["__name__"]
        except:
            modname = "?"
        code = frame.f_code
        filename = code.co_filename
        funcname = code.co_name
        sourceline = linecache.getline(filename, lineno)
        sourceline = sourceline.strip()
        if funcname in ("?", "", None):
            item = "%s, line %d: %s" % (modname, lineno, sourceline)
        else:
            item = "%s.%s(...), line %d: %s" % (modname, funcname,
                                             lineno, sourceline)
        return item
项目:LIE    作者:EmbraceLife    | 项目源码 | 文件源码
def __iter__(self):
        """ Return an iterator to the data. Yield the value for self.key
        from each object
        """
        start = 0
        while start < self.num_entries:
            end = min(self.num_entries, start + self.chunk_size)

            # linecache line numbering starts at 1
            batch = [
                json.loads(
                    linecache.getline(
                        self.source,
                        i + 1
                    ).strip()
                )[self.key]
                for i in self.indices[start:end]
            ]

            yield batch
            start = end

    ###########################################################################
项目:LIE    作者:EmbraceLife    | 项目源码 | 文件源码
def __iter__(self):
        """ Return an iterator to the data. Get the value (tensor) for self.key
        from each object and yield batches of these tensors
        """
        start = 0
        while start < self.num_entries:
            end = min(self.num_entries, start + self.chunk_size)

            # linecache line numbering starts at 1
            batch = [
                json.loads(linecache.getline(self.source, i + 1).strip())[self.key]
                for i in self.indices[start:end]
            ]

            yield batch
            start = end

    ###########################################################################
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
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
项目:bandit-ss    作者:zeroSteiner    | 项目源码 | 文件源码
def get_code(self, max_lines=3, tabbed=False):
        '''Gets lines of code from a file the generated this issue.

        :param max_lines: Max lines of context to return
        :param tabbed: Use tabbing in the output
        :return: strings of code
        '''
        lines = []
        max_lines = max(max_lines, 1)
        lmin = max(1, self.lineno - max_lines // 2)
        lmax = lmin + len(self.linerange) + max_lines - 1

        tmplt = "%i\t%s" if tabbed else "%i %s"
        for line in moves.xrange(lmin, lmax):
            text = linecache.getline(self.fname, line)

            if isinstance(text, bytes):
                text = text.decode('utf-8', 'ignore')

            if not len(text):
                break
            lines.append(tmplt % (line, text))
        return ''.join(lines)
项目:DeepLearning-MXNet    作者:CNevd    | 项目源码 | 文件源码
def __iter__(self):
        while(True):
            buser = []
            bitem = []
            brate = []
            if (not linecache.getline(self.fname, self.index_start + self.batch_size)):
                return
            for i in range(self.index_start, self.index_start + self.batch_size):
                line = linecache.getline(self.fname, i)
                lines = line.strip().split('::')
                if(len(lines) != 4):
                    continue
                line_user, line_item, line_rate, _ = lines
                buser.append(line_user)
                bitem.append(line_item)
                brate.append(line_rate)
            data_all = [mx.nd.array(buser), mx.nd.array(bitem)]
            label_all = [mx.nd.array(brate)]
            data_names = ['user', 'item']
            label_names = ['rate']
            self.index_start += self.batch_size
            data_batch = Batch(data_names, data_all, label_names, label_all)
            yield data_batch
项目:DeepLearning-MXNet    作者:CNevd    | 项目源码 | 文件源码
def __iter__(self):
        while(True):
            bdata = []
            blabel = []
            if (not linecache.getline(self.fname, self.index_start + self.batch_size)):
                return
            for i in range(self.index_start, self.index_start + self.batch_size):
                line = linecache.getline(self.fname, i)
                line_label, line_data =  line.strip().split('\t',1)
                blabel.append(line_label)
                bdata.append(np.array(line_data.split('\t')))
            data_all = [mx.nd.array(bdata)]
            label_all = [mx.nd.array(blabel)]
            data_names = ['data']
            label_names = ['softmax_label']
            self.index_start += self.batch_size
            data_batch = Batch(data_names, data_all, label_names, label_all)
            yield data_batch
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
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:
            self.message('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] == "'''"):
            self.error('Blank or comment')
            return 0
        return lineno
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def print_tb(tb, limit=None, file=None):
    """Print up to 'limit' stack trace entries from the traceback 'tb'.

    If 'limit' is omitted or None, all entries are printed.  If 'file'
    is omitted or None, the output goes to sys.stderr; otherwise
    'file' should be an open file or file-like object with a write()
    method.
    """
    if file is None:
        file = sys.stderr
    if limit is None:
        if hasattr(sys, 'tracebacklimit'):
            limit = sys.tracebacklimit
    n = 0
    while tb is not None and (limit is None or n < limit):
        f = tb.tb_frame
        lineno = tb.tb_lineno
        co = f.f_code
        filename = co.co_filename
        name = co.co_name
        _print(file,
               '  File "%s", line %d, in %s' % (filename, lineno, name))
        linecache.checkcache(filename)
        line = linecache.getline(filename, lineno, f.f_globals)
        if line: _print(file, '    ' + line.strip())
        tb = tb.tb_next
        n = n+1
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def extract_tb(tb, limit = None):
    """Return list of up to limit pre-processed entries from traceback.

    This is useful for alternate formatting of stack traces.  If
    'limit' is omitted or None, all entries are extracted.  A
    pre-processed stack trace entry is a quadruple (filename, line
    number, function name, text) representing the information that is
    usually printed for a stack trace.  The text is a string with
    leading and trailing whitespace stripped; if the source is not
    available it is None.
    """
    if limit is None:
        if hasattr(sys, 'tracebacklimit'):
            limit = sys.tracebacklimit
    list = []
    n = 0
    while tb is not None and (limit is None or n < limit):
        f = tb.tb_frame
        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
        list.append((filename, lineno, name, line))
        tb = tb.tb_next
        n = n+1
    return list
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def extract_stack(f=None, limit = None):
    """Extract the raw traceback from the current stack frame.

    The return value has the same format as for extract_tb().  The
    optional 'f' and 'limit' arguments have the same meaning as for
    print_stack().  Each item in the list is a quadruple (filename,
    line number, function name, text), and the entries are in order
    from oldest to newest stack frame.
    """
    if f is None:
        try:
            raise ZeroDivisionError
        except ZeroDivisionError:
            f = sys.exc_info()[2].tb_frame.f_back
    if limit is None:
        if hasattr(sys, 'tracebacklimit'):
            limit = sys.tracebacklimit
    list = []
    n = 0
    while f is not None and (limit is None or n < limit):
        lineno = f.f_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
        list.append((filename, lineno, name, line))
        f = f.f_back
        n = n+1
    list.reverse()
    return list
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def set_break(self, filename, lineno, temporary=0, cond = None,
                  funcname=None):
        filename = self.canonic(filename)
        import linecache # Import as late as possible
        line = linecache.getline(filename, lineno)
        if not line:
            return 'Line %s:%d does not exist' % (filename,
                                   lineno)
        if not filename in self.breaks:
            self.breaks[filename] = []
        list = self.breaks[filename]
        if not lineno in list:
            list.append(lineno)
        bp = Breakpoint(filename, lineno, temporary, cond, funcname)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def format_stack_entry(self, frame_lineno, lprefix=': '):
        import linecache, repr
        frame, lineno = frame_lineno
        filename = self.canonic(frame.f_code.co_filename)
        s = '%s(%r)' % (filename, lineno)
        if frame.f_code.co_name:
            s = s + frame.f_code.co_name
        else:
            s = s + "<lambda>"
        if '__args__' in frame.f_locals:
            args = frame.f_locals['__args__']
        else:
            args = None
        if args:
            s = s + repr.repr(args)
        else:
            s = s + '()'
        if '__return__' in frame.f_locals:
            rv = frame.f_locals['__return__']
            s = s + '->'
            s = s + repr.repr(rv)
        line = linecache.getline(filename, lineno, frame.f_globals)
        if line: s = s + lprefix + line.strip()
        return s

    # The following two methods can be called by clients to use
    # a debugger to debug a statement, given as a string.
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def user_line(self, frame):
        import linecache
        name = frame.f_code.co_name
        if not name: name = '???'
        fn = self.canonic(frame.f_code.co_filename)
        line = linecache.getline(fn, frame.f_lineno, frame.f_globals)
        print '+++', fn, frame.f_lineno, name, ':', line.strip()
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def localtrace_trace_and_count(self, frame, why, arg):
        if why == "line":
            # record the file name and line number of every trace
            filename = frame.f_code.co_filename
            lineno = frame.f_lineno
            key = filename, lineno
            self.counts[key] = self.counts.get(key, 0) + 1

            if self.start_time:
                print '%.2f' % (time.time() - self.start_time),
            bname = os.path.basename(filename)
            print "%s(%d): %s" % (bname, lineno,
                                  linecache.getline(filename, lineno)),
        return self.localtrace
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def localtrace_trace(self, frame, why, arg):
        if why == "line":
            # record the file name and line number of every trace
            filename = frame.f_code.co_filename
            lineno = frame.f_lineno

            if self.start_time:
                print '%.2f' % (time.time() - self.start_time),
            bname = os.path.basename(filename)
            print "%s(%d): %s" % (bname, lineno,
                                  linecache.getline(filename, lineno)),
        return self.localtrace
项目:pcap_to_ditg    作者:devenbansod    | 项目源码 | 文件源码
def __generateMapper(self):
        Partitions = self.__readPartitions()

        i = 0
        for p in Partitions.keys():
            endPoints = Partitions[p]
            if os.path.exists(self.list_file):
                for i in range(int(endPoints[0]), int(endPoints[1]) + 1):
                    ip = linecache.getline(self.list_file, i).strip().strip(',')
                    (self.__IpMapDict)[ip] = endPoints[2]
            else:
                print('*** The file \'' + self.list_file + '\' could not be read\n')
                raise IOError('The file \'' + self.list_file + '\' could not be read\n')
项目:swjtu-pyscraper    作者:Desgard    | 项目源码 | 文件源码
def formatwarning(message, category, filename, lineno, line=None):
    """Function to format a warning the standard way."""
    try:
        unicodetype = unicode
    except NameError:
        unicodetype = ()
    try:
        message = str(message)
    except UnicodeEncodeError:
        pass
    s =  "%s: %s: %s\n" % (lineno, category.__name__, message)
    line = linecache.getline(filename, lineno) if line is None else line
    if line:
        line = line.strip()
        if isinstance(s, unicodetype) and isinstance(line, str):
            line = unicode(line, 'latin1')
        s += "  %s\n" % line
    if isinstance(s, unicodetype) and isinstance(filename, str):
        enc = sys.getfilesystemencoding()
        if enc:
            try:
                filename = unicode(filename, enc)
            except UnicodeDecodeError:
                pass
    s = "%s:%s" % (filename, s)
    return s
项目:NYCSL2    作者:HMProgrammingClub    | 项目源码 | 文件源码
def _disable_linecache():
    import linecache
    def fake_getline(*args, **kwargs):
        return ''
    linecache.orig_getline = linecache.getline
    linecache.getline = fake_getline