422

perl -c programfile以前は、Perlプログラムの構文をチェックして、実行せずに終了するために使用していました。Pythonスクリプトに対してこれを行う同等の方法はありますか?

4

9 に答える 9

678

構文をコンパイルして確認できます。

python -m py_compile script.py
于 2011-12-08T20:57:16.520 に答える
66

次のツールを使用できます。

于 2010-11-26T10:29:15.390 に答える
25
import sys
filename = sys.argv[1]
source = open(filename, 'r').read() + '\n'
compile(source, filename, 'exec')

これをchecker.pyとして保存し、を実行しますpython checker.py yourpyfile.py

于 2010-11-26T10:39:11.263 に答える
20

astモジュールを使用した別の解決策は次のとおりです。

python -c "import ast; ast.parse(open('programfile').read())"

Pythonスクリプト内からそれをきれいに行うには:

import ast, traceback

filename = 'programfile'
with open(filename) as f:
    source = f.read()
valid = True
try:
    ast.parse(source)
except SyntaxError:
    valid = False
    traceback.print_exc()  # Remove to silence any errros
print(valid)
于 2019-08-15T11:15:56.190 に答える
10

Pyflakesはあなたが求めることを行い、構文をチェックするだけです。ドキュメントから:

Pyflakesは単純な約束をします。それはスタイルについて文句を言うことは決してなく、誤検知を決して出さないように非常に懸命に努力します。

Pyflakesは、PylintやPycheckerよりも高速です。これは主に、Pyflakesが各ファイルの構文ツリーを個別に検査するだけであるためです。

インストールして使用するには:

$ pip install pyflakes
$ pyflakes yourPyFile.py
于 2020-01-08T19:52:34.723 に答える
9
python -m compileall -q .

現在のディレクトリの下にあるすべてのものを再帰的にコンパイルし、エラーのみを出力します。

$ python -m compileall --help
usage: compileall.py [-h] [-l] [-r RECURSION] [-f] [-q] [-b] [-d DESTDIR] [-x REGEXP] [-i FILE] [-j WORKERS] [--invalidation-mode {checked-hash,timestamp,unchecked-hash}] [FILE|DIR [FILE|DIR ...]]

Utilities to support installing Python libraries.

positional arguments:
  FILE|DIR              zero or more file and directory names to compile; if no arguments given, defaults to the equivalent of -l sys.path

optional arguments:
  -h, --help            show this help message and exit
  -l                    don't recurse into subdirectories
  -r RECURSION          control the maximum recursion level. if `-l` and `-r` options are specified, then `-r` takes precedence.
  -f                    force rebuild even if timestamps are up to date
  -q                    output only error messages; -qq will suppress the error messages as well.
  -b                    use legacy (pre-PEP3147) compiled file locations
  -d DESTDIR            directory to prepend to file paths for use in compile-time tracebacks and in runtime tracebacks in cases where the source file is unavailable
  -x REGEXP             skip files matching the regular expression; the regexp is searched for in the full path of each file considered for compilation
  -i FILE               add all the files and directories listed in FILE to the list considered for compilation; if "-", names are read from stdin
  -j WORKERS, --workers WORKERS
                        Run compileall concurrently
  --invalidation-mode {checked-hash,timestamp,unchecked-hash}
                        set .pyc invalidation mode; defaults to "checked-hash" if the SOURCE_DATE_EPOCH environment variable is set, and "timestamp" otherwise.

構文エラーが見つかった場合、終了値は1です。

C2H5OHに感謝します。

于 2021-04-19T08:25:02.560 に答える
2

おそらく便利なオンラインチェッカーPEP8:http: //pep8online.com/

于 2015-09-10T09:22:19.443 に答える
0

何らかの理由で(私はpy初心者です...)-m呼び出しが機能しませんでした...

だからここにbashラッパー関数があります...

# ---------------------------------------------------------
# check the python synax for all the *.py files under the
# <<product_version_dir/sfw/python
# ---------------------------------------------------------
doCheckPythonSyntax(){

    doLog "DEBUG START doCheckPythonSyntax"

    test -z "$sleep_interval" || sleep "$sleep_interval"
    cd $product_version_dir/sfw/python
    # python3 -m compileall "$product_version_dir/sfw/python"

    # foreach *.py file ...
    while read -r f ; do \

        py_name_ext=$(basename $f)
        py_name=${py_name_ext%.*}

        doLog "python3 -c \"import $py_name\""
        # doLog "python3 -m py_compile $f"

        python3 -c "import $py_name"
        # python3 -m py_compile "$f"
        test $! -ne 0 && sleep 5

    done < <(find "$product_version_dir/sfw/python" -type f -name "*.py")

    doLog "DEBUG STOP  doCheckPythonSyntax"
}
# eof func doCheckPythonSyntax
于 2016-12-27T11:04:30.813 に答える
0

上記の回答に感謝します@RoshOxymoron。Pythonファイルであるdir内のすべてのファイルをスキャンするようにスクリプトを改善しました。したがって、私たちの怠惰な人々はそれにディレクトリを与えるだけで、Pythonであるそのディレクトリ内のすべてのファイルをスキャンします。

import sys
import glob, os

os.chdir(sys.argv[1])
for file in glob.glob("*.py"):
    source = open(file, 'r').read() + '\n'
    compile(source, file, 'exec')

Save this as checker.py and run python checker.py ~/YOURDirectoryTOCHECK

于 2020-09-10T20:19:38.207 に答える