检查Python代码中的错误
我可以通过一些库来检查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
有没有类似pylint或pyflakes的Python库,可以在不编译代码的情况下进行代码检查呢?谢谢你的帮助。
更新
我会用一个简单的例子来解释我的意思。我有一个变量“codeString”,它包含了Python源代码。我必须分析这段代码(不创建任何文件和执行代码,但我可以编译代码),并检测所有关于代码块不正确的警告。我们来看看pyflakes模块,了解它是如何工作的。
在“pyflakes.api”模块中,有一个叫“check”的函数。
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文件的解决方案。
1 个回答
0
内置的“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)