예제 #1
0
def pyflakes(codeString, filename):
    """
    Check the Python source given by C{codeString} for flakes.
    """
    # First, compile into an AST and handle syntax errors.
    try:
        tree = compile(codeString, filename, "exec", _ast.PyCF_ONLY_AST)
    except SyntaxError as value:
        msg = value.args[0]
        lineno = value.lineno
        # If there's an encoding problem with the file, the text is None.
        if value.text is None:
            # Avoid using msg, since for the only known case, it contains a
            # bogus message that claims the encoding the file declared was
            # unknown.
            msg = "Problem decoding source"
            lineno = 1
        error = Message(filename, lineno)
        error.message = msg + "%s"
        error.message_args = ""
        return [error]
    else:
        # Okay, it's syntactically valid.  Now check it.
        w = Checker(tree, filename)
        w.messages.sort(lambda a, b: cmp(a.lineno, b.lineno))
        return w.messages
예제 #2
0
def check_code(code, name):
    errors = []

    class CustomMessage(object):
        pass

    reporter = modReporter._makeDefaultReporter()
    try:
        tree = compile(code, name, "exec", _ast.PyCF_ONLY_AST)
    except SyntaxError:
        value = sys.exc_info()[1]
        msg = value.args[0]

        (lineno, offset, text) = value.lineno, value.offset, value.text

        # If there's an encoding problem with the file, the text is None.
        if text is None:
            # Avoid using msg, since for the only known case, it contains a
            # bogus message that claims the encoding the file declared was
            # unknown.
            reporter.unexpectedError(name, 'problem decoding source')
        else:
            reporter.syntaxError(name, msg, lineno, offset, text)

        loc = CustomMessage()
        loc.lineno = lineno
        loc.offset = offset
        msg = Message(name, loc)
        msg.message = "SyntaxError"
        errors.append(msg)
    except Exception, e:
        loc = CustomMessage()
        loc.lineno = lineno
        loc.offset = offset
        msg = Message(name, loc)
        msg.message = "Problem decoding source"
        errors.append(msg)

        reporter.unexpectedError(name, 'problem decoding source')
        logger.error("problem decoding source")
        logger.exception()