programing

Python 스크립트를 실행하지 않고 어떻게 구문을 확인할 수 있습니까?

goodcopy 2022. 11. 26. 12:58
반응형

Python 스크립트를 실행하지 않고 어떻게 구문을 확인할 수 있습니까?

저는 예전에perl -c programfilePerl 프로그램의 구문을 확인하고 실행하지 않고 종료합니다.Python 스크립트에 대해 이와 동등한 방법이 있습니까?

구문은 다음과 같이 컴파일하여 확인할 수 있습니다.

python -m py_compile script.py

다음 도구를 사용할 수 있습니다.

import sys
filename = sys.argv[1]
source = open(filename, 'r').read() + '\n'
compile(source, filename, 'exec')

이 파일을 checker.py으로 저장하고 실행합니다.python checker.py yourpyfile.py.

여기 또 다른 해결책이 있습니다.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)

파이플레이크는 당신이 부탁한대로만 해, 구문만 체크해.문서에서:

파이플레이크는 간단한 약속을 한다.그것은 스타일에 대해 불평하지 않을 것이며, 절대로 잘못된 긍정성을 드러내지 않을 것이다.

파이플레이크는 또한 파이린트나 파이체커보다 빠르다.이는 주로 Pyflakes가 각 파일의 구문 트리만 개별적으로 검사하기 때문입니다.

설치 및 사용 방법:

$ pip install pyflakes
$ pyflakes yourPyFile.py
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.
Python 스크립트를 실행하지 않고 어떻게 구문을 확인할 수 있습니까?  -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.

구문 오류가 발견된 경우 exit 값은 1입니다.

C2H5OH 감사합니다.

유용한 온라인 체커 PEP8 : http://pep8online.com/

어떤 이유로 (저는 초보입니다...) -m 콜이 작동하지 않았습니다.

여기 bash wrapper func가 있습니다.

# ---------------------------------------------------------
# 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

위의 답변 @Rosh Oxymoron 덕분입니다.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

언급URL : https://stackoverflow.com/questions/4284313/how-can-i-check-the-syntax-of-python-script-without-executing-it

반응형