【问题标题】:Check python code for errors检查python代码是否有错误
【发布时间】:2014-07-14 15:08:48
【问题描述】:

我可以通过一些库检查 python 文件或模块是否有错误,例如:pylint、pychecker、pyflakes 等。在大多数情况下,我必须指定文件或目录进行检查。例如:

pylint directory/mymodule.py

没关系,但对我来说还不够。我想分析分离的代码块并获取所有检测到的错误和警告。所以,我必须从我自己的模块中调用一个 python 代码分析器作为程序的一部分。

import some_magic_checker

code = '''import datetime; print(datime.datime.now)'''
errors = some_magic_checker(code)
if len(errors) == 0:
    exec(code)  # code has no errors, I can execute its
else:
    print(errors)  # display info about detected errors

是否存在一些 python 库,如 pylint 或 pyflakes,它们提供了 python 代码检查功能无需代码编译?感谢您的帮助。


UPD

我将尝试在这个简单的例子中解释我的意思。我有一个变量“codeString”,其中包含 python 源代码。我必须分析此代码(无需任何文件创建和代码执行,但我可以编译代码)并检测有关不正确代码块的所有警告。让我们看看 pyflakes 模块的内部并了解它是如何工作的。

模块“pyflakes.api”中有一个“检查”功能。

from pyflakes import checker
from pyflakes import reporter as modReporter
import _ast
import sys

def check(codeString, filename):
    reporter = modReporter._makeDefaultReporter()
    try:
        tree = compile(codeString, filename, "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(filename, 'problem decoding source')
        else:
            reporter.syntaxError(filename, msg, lineno, offset, text)
        return 1
    except Exception:
        reporter.unexpectedError(filename, 'problem decoding source')
        return 1
    # Okay, it's syntactically valid.  Now check it.
    w = checker.Checker(tree, filename)
    w.messages.sort(key=lambda m: m.lineno)
    for warning in w.messages:
        reporter.flake(warning)
    return len(w.messages)

你怎么看,这个函数不能只用一个参数“codeString”,我们还必须提供第二个参数“filename”。这是我最大的问题,我没有任何文件,只有字符串变量中的 Python 代码。

据我所知,pylint、pychecker、pyflakes 和所有库仅适用于创建的文件。所以我试图找到一些不需要链接到 Python 文件的解决方案。

【问题讨论】:

  • pyflakes 不编译任何代码。
  • 为什么代码编译很重要——一般来说,检测错误和警告的唯一方法是做大部分的编译工作。
  • def some_magic_checker(code):将代码存储在tmp文件中;运行各种检查器;返回抓取的错误?
  • 我可以理解你不想执行,但是编译不等于执行。只要您的模块没有副作用,您就可以通过打开 python 交互式控制台并导入它来非常简单地编译代码。
  • 我明白你在做什么——虽然仍然不确定为什么,但把它放在一边——你能不使用编译功能吗——相对容易使用。

标签: python pylint pychecker


【解决方案1】:

内置函数“compile”允许创建已编译的代码或 AST 对象并在不创建文件和执行代码的情况下捕获一些错误。我们必须将'<string>' 值作为第二个参数传递,因为代码不是从文件中读取的。

>>> def execute(code_string):
>>>    output = list()
>>>    try:
>>>        tree = compile(code_string, '<string>', 'exec')
>>>    except Exception as e:
>>>        print(e)
>>>    else:
>>>        exec(tree)
>>> # Now I can check code before calling the "exec" function
>>> code_string = 'print("Hello_World!")'
>>> execute(code_string)  # All is ok
Hello_World!
>>> code_string = 'ERROR! print("Hello_World!")'
>>> execute(code_string)  # This code will not executed
invalid syntax (<string>, line 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多