pylint、pychecker、pyflakes などのいくつかのライブラリを使用して、python ファイルまたはモジュールのエラーをチェックできます。ほとんどの場合、チェックするファイルまたはディレクトリを指定する必要があります。例えば:
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
簡単な例で私が何を意味するのかを説明しようとします。Pythonソースコードを含む1つの変数「codeString」があります。このコードを分析し (ファイルの作成やコードの実行は必要ありませんが、コードをコンパイルすることはできます)、コードの不適切なブロックに関するすべての警告を検出する必要があります。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)
ご覧のとおり、この関数は 1 つのパラメーター「codeString」だけでは機能しません。2 番目のパラメーター「filename」も指定する必要があります。そして、これが私の最大の問題です。ファイルはなく、文字列変数の Python コードだけです。
私が知っているpylint、pychecker、pyflakes、およびすべてのライブラリは、作成されたファイルでのみ機能します。だから私は、Pythonファイルへのリンクを必要としないいくつかの解決策を見つけようとしています.